您的位置:首页 > 其它

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

2015-10-30 11:56 162 查看
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[0];
m2 = 0;
count1 = 1;
count2 = 0;
for(int i = 1; i < sz; ++i){
if(m1 == nums[i])
count1++;
else if(m2 == nums[i])
count2++;
else if(count1 == 0){
count1++;
m1 = nums[i];
}else if(count2 == 0){
count2++;
m2 = nums[i];
}else{
count1--;
count2--;
}
}
count1 = count2 = 0;
for(int i = 0; i < sz; ++i){
if(nums[i] == m1) ++count1;
if(nums[i] == m2) ++count2;
}
if(count1 > sz/3) ret.push_back(m1);
if(m1 != m2)
if(count2 > sz/3) ret.push_back(m2);
return ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: