229. Majority Element II (重要!)

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.

若num与n1或n2相同,则将其对应的出现次数加1

否则,若c1或c2为0,则将其置为1,对应的候选众数置为num

否则,将c1与c2分别减1

最后,再统计一次候选众数在数组中出现的次数,若满足要求,则返回之。

class Solution {
public:
	vector majorityElement(vector& nums) {
		vector res;
		int len = nums.size();
		if (len ==0){
			return res;
		}
		if (len == 1){
			res.push_back(nums[0]);
			return res;
		}

		int m1=nums[0], cnt1 = 1;
		int m2=0, cnt2 = 0;
		
		for (int i = 1; i < len; i++){
			if (nums[i] == m1){//顺序不能乱
				cnt1++;
			}
			else if (nums[i] == m2){
				cnt2++;
			}
			else if (cnt1 == 0){
				m1 = nums[i];
				cnt1 = 1;
			}
			else if (cnt2 == 0){
				m2 = nums[i];
				cnt2 = 1;
			}
			else{
				cnt1--;
				cnt2--;
			}
		}

		cnt1 = 0, cnt2 = 0;
		for (int i = 0; i < len; i++){
			if (nums[i] == m1){
				cnt1++;
			}
			if (nums[i] == m2){
				cnt2++;
			}
		}

		if (cnt1>len / 3){
			res.push_back(m1);
		}
		if (cnt2 > len / 3){
			if (m2!=m1)
				res.push_back(m2);
		}
		
		return res;
	}
};


你可能感兴趣的:(leetcode)