您的位置:首页 > 其它

LeetCode:169. Majority Element

2017-03-18 11:20 351 查看
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次那么return,这种方法结果出现超时。上网查找一下,发现有个很好的
方法:每找出两个不同的element,就成对删除即count--,最终剩下的一定就是所求的。
AC:

class Solution {
public:
int majorityElement(vector<int>& nums) {
int elem = 0;
int count = 0;
for(int i = 0; i < nums.size(); i++)  {
if(count == 0)  {
elem = nums[i];
count = 1;
}
else    {
if(elem == nums[i])
count++;
else
count--;
}

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