一、题目

image.png

二、分析与解答

  1. map 统计每个元素的个数

    1. class Solution {
    2. public int majorityElement(int[] nums) {
    3. int n = nums.length;
    4. if(n == 0) return -1;
    5. HashMap<Integer,Integer> map = new HashMap<>();
    6. for(int num : nums) {
    7. map.put(num, map.getOrDefault(num, 0) + 1);
    8. }
    9. for(Map.Entry<Integer,Integer> entry : map.entrySet()) {
    10. int key = entry.getKey();
    11. int value = entry.getValue();
    12. if(value > n/2) {
    13. return key;
    14. }
    15. }
    16. return -1;
    17. }
    18. }

    效率: 时间复杂度O(n)、空间复杂度O(n)
    image.png

  2. Boyer-Moore 投票算法

Boyer-Moore 投票算法的基本思想是:在每一轮投票过程中,从数组中删除两个不同的元素,直到投票过程无法继续,此时数组为空或者数组中剩下的元素都相等。

  • 如果数组为空,则数组中不存在主要元素;
  • 如果数组中剩下的元素都相等,则数组中剩下的元素可能为主要元素。

Boyer-Moore 投票算法的步骤如下:
1、维护一个候选主要元素candidate 和候选主要元素的出现次数 count,初始时 candidate 为任意值,count=0;
2、遍历数组 nums 中的所有元素,遍历到元素 x 时,进行如下操作:

  • 如果count=0,则将 x 的值赋给candidate,否则不更新 candidate 的值;

  • 如果 x=candidate,则将 count 加 1,否则将 count 减 1。

3、遍历结束之后,如果数组nums 中存在主要元素,则 candidate 即为主要元素,否则 candidate 可能为数组中的任意一个元素。

由于不一定存在主要元素,因此需要第二次遍历数组,验证 candidate 是否为主要元素。第二次遍历时,统计 candidate 在数组中的出现次数,如果出现次数大于数组长度的一半,则 candidate 是主要元素,返回 candidate,否则数组中不存在主要元素,返回 −1。

为什么当数组中存在主要元素时,Boyer-Moore 投票算法可以确保得到主要元素?

在Boyer-Moore 投票算法中,遇到相同的数则将 count 加 1,遇到不同的数则将 count 减 1。根据主要元素的定义,主要元素的出现次数大于其他元素的出现次数之和,因此在遍历过程中,主要元素和其他元素两两抵消,最后一定剩下至少一个主要元素,此时candidate 为主要元素,且 count≥1。

  1. class Solution {
  2. public int majorityElement(int[] nums) {
  3. int candidate = -1;
  4. int count = 0;
  5. for (int num : nums) {
  6. if (count == 0) {
  7. candidate = num;
  8. }
  9. if (num == candidate) {
  10. count++;
  11. } else {
  12. count--;
  13. }
  14. }
  15. count = 0;
  16. int length = nums.length;
  17. for (int num : nums) {
  18. if (num == candidate) {
  19. count++;
  20. }
  21. }
  22. return count * 2 > length ? candidate : -1;
  23. }
  24. }