您的位置:首页 > 其它

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  分治