169. Majority Element
2016-09-09 22:56
141 查看
169. Majority Element
题目原文Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-empty and the majority element always exist in the array.
解法1 :分治法
思路求数组的众数,可以转而求前半段数组的众数和后半段的众数,然后比较两个众数的频率,较大者则为该数组的众数。
代码
class Solution { public: int majority(vector<int>& nums,int begin,int end){ if(begin==end) return nums[begin]; int mid=(end+begin)/2; int l=majority(nums,begin,mid); int r=majority(nums,mid+1,end); if(l==r) return l; int lcnt=0,rcnt=0; for(int i=begin;i<=end;i++){ if(l==nums[i]) lcnt++; if(r==nums[i]) rcnt++; } if(lcnt>rcnt) return l; return r; } int majorityElement(vector<int>& nums) { return majority(nums,0,nums.size()-1); } };
原数组分成左右两支,且若两支的众数不等时需要遍历数组,遍历数组时需要O(n)时间。故时间复杂度为:T(n)=2T(n/2)+O(n)=O(nlogn)
运行时间:16ms
解法2:排序求中值
思路因为众数的个数至少为数组元素的一半,所以将数组排序后,中间元素肯定为众数。
代码
class Solution { public: int majorityElement(vector<int>& nums) { sort(nums.begin(),nums.end()); int len=nums.size(); return nums[len/2]; } };
时间复杂度取决于sort()函数,复杂度为O(nlogn)。
运行时间:36ms
相关文章推荐
- LeetCode(169)Majority Element
- Leetcode Algorithms - Divide and Conquer:169. Majority Element
- [Leetcode]#169 Majority Element
- 169. Majority Element
- 169. Majority Element
- 【LEETCODE】169-Majority Element
- 169.Majority Element
- 2018.03.07 leetcode 打卡 #169. Majority Element
- 【LeetCode】169. Majority Element (多数投票算法 & 算法迁移能力)
- 169. Majority Element
- 169. Majority Element
- 169. Majority Element My Submissions Question
- leetcode 169 Majority Element C++
- Leetcode解题报告:169. Majority Element
- LeetCode 169. Majority Element 解题报告
- 169. Majority Element
- 169. Majority Element (寻找多数元素)
- 169. Majority Element
- 169. Majority Element
- leetcode题解-169. Majority Element && 189. Rotate Array