题目描述:

求众数

解法1:

        摩尔投票法,这种方法就是因为题目给出一定存在一个数其个数是大于n/2的,所以设置一个投票计数器,选定第一个值作为起始值,然后后面的值如果是这个值那么计数加一,如果不等,那么计数减一,当计数器的值为零时,选取当前值作为新值继续计数。这样最后计数器不为零对应的值一定是出现次数大于一半的值。

public int majorityElement(int[] nums) {
    int result = 0;
    int count = 0;
    for (int i:nums){
        if (result == i) 
            count++;
        else if(count!=0) 
            count--;
        else{
            result = i;
            count = 1;
        }
    }
    return result;
}

--------------------- 
作者:哪得小师弟 
来源:CSDN 
原文:https://blog.csdn.net/x603560617/article/details/83903678 

 解法2:

        解题思路:定义一个集合,遍历数组,将数组放入集合并且记录元素出现的次数,众数是出现次数大于n/2的元素。

    public int majorityElement2(int[] nums) {
	LinkedHashMap<Integer, Integer> map = new LinkedHashMap<>();//定义一个集合
        //遍历数组,将数组放入集合并且记录出现的次数
        for (int num : nums) {
            if (map.get(num) != null) {
                map.put(num, map.get(num) + 1);
            } else {
                map.put(num, 1);
            }
        }
        //遍历集合  
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() > nums.length / 2) {
                return entry.getKey();
            }
        }
        return 0;
    }

--------------------- 
作者:小熊维尼446
来源:CSDN 
原文:https://blog.csdn.net/xxwn446/article/details/88235911

相关文章:

  • 2022-01-16
  • 2021-09-25
  • 2021-08-28
  • 2021-10-16
  • 2022-12-23
  • 2022-12-23
  • 2022-01-04
猜你喜欢
  • 2021-04-10
  • 2022-12-23
  • 2021-08-12
  • 2021-05-19
  • 2021-08-06
  • 2021-12-04
  • 2021-05-18
相关资源
相似解决方案