解法1: 先把nums[0]设为candidate,count=1,挨个往后比,如果相同则count++, 否则count–。当count=0时,则将candidate设为当前元素。
#include <iostream>
#include <vector>
using namespace std;
int majorityElement(vector<int>& nums) {
int count=1;
int candidate=nums[0];
for (int i=1; i<nums.size(); ++i) {
if (count==0) candidate=nums[i];
if (nums[i]==candidate) count++;
else count--;
}
return candidate;
}
int main()
{
vector<int> a1={3,2,3};
cout<<majorityElement(a1)<<endl;
vector<int> a2={2,2,1,1,1,2,2};
cout<<majorityElement(a2)<<endl;
vector<int> a3={3,3,4};
cout<<majorityElement(a3)<<endl;
return 0;
}
解法2:待定
解法3:待定