169. 多数元素

难度简单1159收藏分享切换为英文接收动态反馈
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。

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


进阶:

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

思路:不同元素相互抵消

  1. class Solution {
  2. public int majorityElement(int[] nums) {
  3. int cnt = 0, res = -1;
  4. for (int x : nums) {
  5. if (cnt == 0)
  6. res = x;
  7. if (res == x)
  8. cnt++;
  9. else
  10. cnt--;
  11. }
  12. return res;
  13. }
  14. }

229. 求众数 II

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


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

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

提示:

  • 1 <= nums.length <= 5 * 10
  • -10 <= nums[i] <= 10


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

    思路:**每三个不同元素相互抵消

    1. class Solution {
    2. public List<Integer> majorityElement(int[] nums) {
    3. int v1 = 0, v2 = 0, num1 = 0, num2 = 0;
    4. for (int x : nums) {
    5. if (v1 > 0 && x == num1)
    6. v1++;
    7. else if (v2 > 0 && x == num2)
    8. v2++;
    9. else if (v1 == 0) {
    10. num1 = x;
    11. v1++;
    12. }
    13. else if (v2 == 0) {
    14. num2 = x;
    15. v2++;
    16. }
    17. else {
    18. v1--;
    19. v2--;
    20. }
    21. }
    22. int c1 = 0, c2 = 0;
    23. for (int x : nums) {
    24. if (v1 > 0 && x == num1)
    25. c1++;
    26. if (v2 > 0 && x == num2)
    27. c2++;
    28. }
    29. List<Integer> res = new ArrayList<>();
    30. if (c1 > nums.length / 3)
    31. res.add(num1);
    32. if (c2 > nums.length / 3)
    33. res.add(num2);
    34. return res;
    35. }
    36. }