229. 求众数 II-数组/众数-中等

问题描述

给定一个大小为 n 的数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。

进阶:尝试设计时间复杂度为 O(n)、空间复杂度为 O(1)的算法解决此问题。

示例 1:

输入:[3,2,3]
输出:[3]
示例 2:

输入:nums = [1]
输出:[1]
示例 3:

输入:[1,1,1,3,3,2,2,2]
输出:[1,2]
 

提示:

1 <= nums.length <= 5 * 104
-109 <= nums[i] <= 109

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/majority-element-ii

解答

//投票法plus
class Solution {
    public List<Integer> majorityElement(int[] nums) {
        int n = nums.length;
        List<Integer> res = new ArrayList<>();
        if(n == 0)return res;
        int cand1 = 0, cand2 = 0, c1 = 0, c2 = 0;
        for(int i:nums){
            if(c1 == 0){
                if(c2 != 0 && cand2 == i){
                    c2++;
                    continue;
                }else{
                    cand1 = i;
                    c1++;
                    continue;
                }
            }
            if(cand1 == i){
                c1++;
                continue;
            }
            if(c2 == 0){
                cand2 = i;
                c2++;
                continue;
            }
            if(cand2 == i){
                c2++;
                continue;
            }

            c1--;
            c2--;
        }
        int min = n/3, num1 = 0, num2 = 0;
        for(int i:nums){
            if(cand1 == i)num1++;
            else if(cand2 == i)num2++;
        }

        if(num1>min)res.add(cand1);
        if(num2>min)res.add(cand2);
        return res;
    }
}
原文地址:https://www.cnblogs.com/xxxxxiaochuan/p/13814157.html