共两道:
1、数组中,出现次数超过一半的元素(一定存在):LeetCode - 169. Majority Element
2、数组中,出现次数超过 n / 3 的元素(不一定存在):LeetCode - 229. Majority Element II
一、LeetCode - 169. Majority Element
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
Input: [3,2,3] Output: 3
Input: [2,2,1,1,1,2,2] Output: 2
很简单,就是既然一个数出现次数超过数组长度的一半,比如这个数是 a,那就相当于用一个 a 去和一个不是 a 的数抵消,最后数组肯定还剩 >= 1 个 a,代码如下(O(N)):
int majorityElement(vector<int>& nums) {
int cur = nums[0], cur_cnt = 1;
for(int i = 1; i < nums.size(); ++i)
if(nums[i] != cur){
if(cur_cnt == 1) cur = nums[i];
else --cur_cnt;
}
else
++cur_cnt;
return cur;
}
二、LeetCode - 229. Majority Element II
Given an integer array of size n, find all elements that appear more than ⌊ n / 3 ⌋ times.
Note: The algorithm should run in linear time and in O(1) space.
Input: [3,2,3] Output: [3]
Input: [1,1,1,3,3,2,2,2] Output: [1,2]
⌊ n / 3 ⌋ 是下取整,用 C++ 的 / 就可以了。和上边的题一样,我们先认为这两个数存在(如果存在,最多存在两个),然后取到最后存活下来的两个数,但是由于不一定存在,所以还需要在遍历一次检查是否确实超过了 n / 3,代码如下(O(N) time, O(1) space):
vector<int> majorityElement(vector<int>& nums) {
const int len = nums.size();
int a = INT_MIN, a_cnt = 0, b = INT_MIN, b_cnt = 0;
for(const int& n : nums) {
if(n == a)
++a_cnt;
else if(n == b)
++b_cnt;
else if(a_cnt == 0) {
a_cnt = 1;
a = n;
}
else if(b_cnt == 0) {
b_cnt = 1;
b = n;
}
else {
--a_cnt;
--b_cnt;
}
}
a_cnt = 0, b_cnt = 0;
for(const int& n : nums) {
if(n == a) ++a_cnt;
else if(n == b) ++b_cnt;
}
vector<int> res;
if(a_cnt > len / 3) res.push_back(a);
if(b_cnt > len / 3) res.push_back(b);
return res;
}