您的位置:首页 > 其它

leetcode-169-Majority Element

2015-06-30 20:20 309 查看


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.

找出数组里面出现次数最多的那个数(出现次数大于n/2)。

对数组排序,因为出现次数最多的数的次数大于n/2 ,故排序后最 中间的数,必为出现次数最多的数。
class Solution {
public:
int majorityElement(vector<int> &num) {
int n = num.size();
sort(num.begin(),num.end());
return num[n/2];
}
};
因为要排序,所以 复杂度为O(nlogn)

也可以用复杂度为O(n)的算法

即,每找到两个不同的数,就成对删除,出现次数最多的元素最终会留下。因为次数做多的数出现次数大于n/2,所以最坏的情况下,也可以找出。

class Solution {
public:
int majorityElement(vector<int> &num) {
int elem=0,count_=0;
for(int i=0;i<num.size();i++){
if(!count_){   // count_==0  则将当前的数赋给elem
elem=num[i];
count_=1;
}
else{
if(elem==num[i])   //  当前元素num[i]==elem 则count_++;
count_++;
else count_--;    // 否则 成对删除
}
}
return elem;
}
};


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