您的位置:首页 > 编程语言 > Go语言

【leetcode】Majority Element II,Majority element algorithm

2015-09-08 17:04 465 查看
My idea comes from Majority Vote algroithm(http://www.cs.utexas.edu/~moore/best-ideas/mjrty/index.html) .Now we vote two numbers simultaneously. if the next number is differents from them both.then the two numbers’ votes minus one. If some number’s vote comes zero,then vote the next number.Every time vote minus,it is the same that we remove the three numbers from the array.And the majority elemnts of original still are the majority elements in the end. So check t1 and t2 are the majority elements of original array at last.

vector<int> majorityElement(vector<int>& nums) {
int t1,t2,n1=0,n2=0;  //numbers t1 and t2,votes' numbers n1,and n2.
for(int i=0;i<nums.size();++i)
{
if(n1!=0&&t1==nums[i]){++n1;continue;}
if(n2!=0&&t2==nums[i]){++n2;continue;}
if(n1==0){ t1=nums[i];++n1;continue;}
if(n2==0){ t2=nums[i];++n2;continue;}
--n1;--n2;
}
int z1=0,z2=0;
for(int i=0;i<nums.size();++i)
{
if(n1>0){ if(nums[i]==t1) ++z1;}
if(n2>0) {if(nums[i]==t2) ++z2;}
}
vector<int> ret;
//check t1 and t2.
if(z1>nums.size()/3) ret.push_back(t1);
if(z2>nums.size()/3) ret.push_back(t2);
return ret;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: