169. 多数元素

给定一个大小为 n 的数组 nums ,返回其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例 1:

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

示例 2:

输入:nums = [2,2,1,1,1,2,2]
输出:2

 提示:

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

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

    public int majorityElement(int[] nums) {
        return method1(nums, nums.length);
    }

    /**
     * 投票算法
     * 1 ms
     * 复杂度O(n)
     */
    public int method1(int[] nums, int n) {
        int cache = 0, count = 0;
        for (int num : nums) {
            // 由于众数超过一半,所以肯定有一个阈值下count会大于0,对应的数就是众数
            if (count == 0) {
                cache = num;
            }
            count += (num == cache ? 1 : -1);
        }
        return cache;
    }

Tags:

No responses yet

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

🛡️ 闽ICP备2024065179号-3