LeetCode刷题实战229:求众数 II
共 4111字,需浏览 9分钟
·
2021-04-06 11:33
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
Follow-up: Could you solve the problem in linear time and in O(1) space?
示例
示例 1:
输入:[3,2,3]
输出:[3]
示例 2:
输入:nums = [1]
输出:[1]
示例 3:
输入:[1,1,1,3,3,2,2,2]
输出:[1,2]
解题
class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> res = new ArrayList<>();
int r1 = 0, r2 = 0, c1 = 0, c2 = 0, n = nums.length;
for(int i = 0; i < n; i++){
int x = nums[i];
//如果仓库中有值,需要先判断,否则无法处理所有数都相同的情况
//前两个if和后面的if顺序不能调换
if(c1 != 0 && x == r1){
c1++;
}else if(c2 != 0 && x == r2){
c2++;
}else if(c1 == 0){
r1 = x;
c1++;
}else if(c2 == 0){
r2 = x;
c2++;
}else{
c1--;
c2--;
}
}
c1 = 0;
c2 = 0;
for(int i = 0; i < n; i++){
int x = nums[i];
if(r1 == x) c1++;
else if(r2 == x) c2++;
}
if(c1 > n/3) res.add(r1);
if(c2 > n/3) res.add(r2);
return res;
}
}