LeetCode OJ:Majority Element II(主元素II)

时间:2021-07-25 19:55:46

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

求主元素,这次的是大于sz/3就算是主元素,可以分为两轮查找,第一轮先查找元素数目较多的两个元素(可能不属于主元素),第二次再遍历来查找上面两个元素是否符合条件,代码如下:

 class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
int m1, m2;
int count1, count2;
vector<int> ret;
int sz = nums.size();
if(!sz) return ret;
m1 = nums[];
m2 = ;
count1 = ;
count2 = ;
for(int i = ; i < sz; ++i){
if(m1 == nums[i])
count1++;
else if(m2 == nums[i])
count2++;
else if(count1 == ){
count1++;
m1 = nums[i];
}else if(count2 == ){
count2++;
m2 = nums[i];
}else{
count1--;
count2--;
}
}
count1 = count2 = ;
for(int i = ; i < sz; ++i){
if(nums[i] == m1) ++count1;
if(nums[i] == m2) ++count2;
}
if(count1 > sz/) ret.push_back(m1);
if(m1 != m2)
if(count2 > sz/) ret.push_back(m2);
return ret;
}
};