LeetCode-每日一题 229. 求众数 II [Java实现] [极速]

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

示例 1:

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

方法一:排序

        已知在 n >= 3 的情况下,所求众数在数组中经排序后所占长度一定 > n/3(例如 [1,1,1,2,2,3,3] 7/3=2)。借此特性我们可以根据 当前位数值(nums[index])与下个阈值长度处值(nums[index+threshold])是否相等来判断index处起的一串数字是否为众数。加上一些特殊情况判断与边界区分,我们很容易编写以下代码:

    public List<Integer> majorityElement(int[] nums) {
        if (nums.length == 1) return Collections.singletonList(nums[0]);
        else if (nums.length == 2) {
            if (nums[0] == nums[1]) return Collections.singletonList(nums[0]);
            else return Arrays.asList(nums[0], nums[1]);
        }
        int threshold = nums.length/3;
        Arrays.sort(nums);
        int index = 0, limit = nums.length-1, next;
        HashSet<Integer> result = new HashSet<>(1 << 2);
        while (index < limit) {
            if ((next = index+threshold) <= limit && nums[index] == nums[next]) {
                index += threshold;
                result.add(nums[index]);
            } else ++index;
        }
        return new ArrayList<>(result);
    }

方法二:摩尔投票法

        第一个方法的空间复杂度是O(1),时间复杂度确是O(N*logN),如果想对时间复杂度进行进一步优化,我们可以选用以下思路:

        易证 对于任意长度为n的序列,其长度>n/3的子序列的个数最多不超过两个。假设现在数组中有两个众数子序列 A、B和一个包含其它杂项的子序列C,那么一定有 A.length > C.length && B.length > C.length故我们可以对该序列中的任意两不等项相消直到剩下两个可能的项,然后对这两个项的实际长度进行计算验证得出答案。

  • 如果是两个众数,那么任意一个众数的序列长度在 (n/3, n/2]

  • 如果是一个众数,那么只有一个众数的序列长度在 (n/2, n)

    public List<Integer> majorityElement(int[] nums) {
        List<Integer> res = new ArrayList<>();
        if (nums == null || nums.length == 0) return res;
        int cand1 = nums[0], count1 = 0;
        int cand2 = nums[0], count2 = 0;

        for (int num : nums) {
            if (cand1 == num) {
                count1++;
                continue;
            }
            if (cand2 == num) {
                count2++;
                continue;
            }
            if (count1 == 0) {
                cand1 = num;
                count1++;
                continue;
            }
            if (count2 == 0) {
                cand2 = num;
                count2++;
                continue;
            }
            count1--;
            count2--;
        }

        // 计数阶段
        count1 = 0;
        count2 = 0;
        for (int num : nums) {
            if (cand1 == num) count1++;
            else if (cand2 == num) count2++;
        }

        if (count1 > nums.length / 3) res.add(cand1);
        if (count2 > nums.length / 3) res.add(cand2);

        return res;
    }
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值