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.
思路:
【LeetCode 169】Majority Element 的拓展,这回要求的是出现次数超过三分之一次的数字咯,动动我们的大脑思考下,这样的数最多会存在几个呢,当然是2个嘛。因此,接着上一题的方法做,只不过这回要投两个票啦,而且最后还得检查这两个投票结果是不是真的满足都超过三分之一,因为这一题题目什么都没有保证,所以答案可能有0个、1个、2个。
C++:
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
vector<int> ret; int len = nums.size();
if(len == )
return ret; int m = , n = , cm = , cn = ;
for(int i = ; i < len; i++)
{
int val = nums[i];
if(m == val)
cm++;
else if(n == val)
cn++;
else if(cm == )
{
m = val;
cm = ;
}
else if(cn == )
{
n = val;
cn = ;
}
else
{
cm--;
cn--;
}
} cm = cn = ; for(int i = ; i < len; i++)
{
if(nums[i] == m)
cm++;
else if(nums[i] == n)
cn++;
} if(cm * > len)
ret.push_back(m);
if(cn * > len)
ret.push_back(n); return ret;
}
};
Python:
class Solution:
# @param {integer[]} nums
# @return {integer[]}
def majorityElement(self, nums):
m, n, cm, cn = 0, 0, 0, 0
ret = [] for val in nums:
if m == val:
cm = cm + 1
elif n == val:
cn = cn + 1
elif cm == 0:
m = val
cm = 1
elif cn == 0:
n = val
cn = 1
else:
cm = cm - 1
cn = cn - 1 cm, cn = 0, 0 for val in nums:
if m == val:
cm = cm + 1
elif n == val:
cn = cn + 1 if cm * 3 > len(nums):
ret.append(m)
if cn * 3 > len(nums):
ret.append(n) return ret