题目

类型:Array
image.png

解题思路

这道题用 map 方法去做很简单,但是题目描述要求要达到线性的时间复杂度,还有常量级的空间复杂度。
这个就变得有点难了,不过有更好的算法可以达到题目的要求——摩尔投票法。
https://leetcode-cn.com/problems/majority-element-ii/solution/liang-fu-dong-hua-yan-shi-mo-er-tou-piao-fa-zui-zh/
看视频会理解的快点

代码

  1. class Solution {
  2. public List<Integer> majorityElement(int[] nums) {
  3. // 创建返回值
  4. List<Integer> res = new ArrayList<>();
  5. if (nums == null || nums.length == 0) return res;
  6. // 初始化两个候选人candidate,和他们的计票
  7. int cand1 = nums[0], count1 = 0;
  8. int cand2 = nums[0], count2 = 0;
  9. // 摩尔投票法,分为两个阶段:配对阶段和计数阶段
  10. // 配对阶段
  11. for (int num : nums) {
  12. // 投票
  13. if (cand1 == num) {
  14. count1++;
  15. continue;
  16. }
  17. if (cand2 == num) {
  18. count2++;
  19. continue;
  20. }
  21. // 第1个候选人配对
  22. if (count1 == 0) {
  23. cand1 = num;
  24. count1++;
  25. continue;
  26. }
  27. // 第2个候选人配对
  28. if (count2 == 0) {
  29. cand2 = num;
  30. count2++;
  31. continue;
  32. }
  33. count1--;
  34. count2--;
  35. }
  36. // 计数阶段
  37. // 找到了两个候选人之后,需要确定票数是否满足大于 N/3
  38. count1 = 0;
  39. count2 = 0;
  40. for (int num : nums) {
  41. if (cand1 == num) count1++;
  42. else if (cand2 == num) count2++;
  43. }
  44. if (count1 > nums.length / 3) res.add(cand1);
  45. if (count2 > nums.length / 3) res.add(cand2);
  46. return res;
  47. }
  48. }