您的位置:首页 > 其它

[LeetCode]169. Majority Element寻找数组中超过一半的那个数

2016-09-18 22:15 489 查看
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.

Credits:

Special thanks to @ts for adding this problem and creating all test cases.

Subscribe to see which companies asked this question
每找出两个不同的element,就成对删除即count--,最终剩下的一定就是所求的。时间复杂度:O(n)

#include<iostream>
#include<string>
#include<vector>
using namespace std;

int majorityElement(vector<int>& nums)
{
int n,count=0,len=nums.size();
for(int i=0;i<len;i++)
{
if(count==0)
{
count++;
n=nums[i];
}
else{
if(nums[i]==n)
count++;
else
count--;
}
}
return n;
}

int main()
{
vector<int> numbers;
numbers.push_back(1);
numbers.push_back(3);
numbers.push_back(3);
cout<<majorityElement(numbers)<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: