LeetCode-169-多数元素

多数元素

题目描述:给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。

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

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/majority-element/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:HashMap

利用java的HashMap,key存不同的数字,value存对应的数字出现的次数:

  • 遍历nums,将每个数字放入HashMap里;
  • 比较得到的HashMap,比较每个数字出现的次数,得到出现次数最多的数字,返回结果。

解法二:摩尔投票算法

摩尔投票算法就是把相异的2个数都消耗掉,由于总是存在多数元素,意味着相异的数消耗掉之后只可能留下那个多数元素。具体过程如下,用result记录最终的那个多数,初始化为数组的第一个元素,count记录这个数字重复的次数:

  • 首先,如果count为0,表示前面的相异的数字都消耗完了,result赋值为当前的数,count为1;
  • 如果count大于0:
    • 如果result和当前元素相等,则count加1;
    • 如果result和当前元素不相等,则count减一,即消耗掉一对相异的数。

最终result一定是那个多数元素。

import java.util.HashMap;
import java.util.Map;

public class LeetCode_169 {
    /**
     * 方法一:HashMap
     *
     * @param nums
     * @return
     */
    public static int majorityElement(int[] nums) {
        Map<Integer, Integer> count = new HashMap<>();
        for (int num : nums) {
            if (count.get(Integer.valueOf(num)) == null) {
                count.put(Integer.valueOf(num), 1);
            } else {
                count.put(Integer.valueOf(num), count.get(Integer.valueOf(num)) + 1);
            }
        }
        int result = -1, maxCount = -1;
        for (Map.Entry<Integer, Integer> integerIntegerEntry : count.entrySet()) {
            if (integerIntegerEntry.getValue() > maxCount) {
                maxCount = integerIntegerEntry.getValue();
                result = integerIntegerEntry.getKey();
            }
        }
        return result;
    }

    /**
     * 方法二:摩尔投票算法
     *
     * @param nums
     * @return
     */
    public static int majorityElement2(int[] nums) {
        int result = nums[0], count = 1;
        for (int i = 1; i < nums.length; i++) {
            if (count == 0) {
                result = nums[i];
                count++;
            } else {
                if (result == nums[i]) {
                    count++;
                } else {
                    count--;
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{10, 9, 9, 9, 10};
        System.out.println(majorityElement(nums));

        System.out.println(majorityElement2(nums));
    }
}

【每日寄语】 所有逆袭,都是有备而来;所有光芒,都是努力埋下的伏笔。

原文地址:https://www.cnblogs.com/kaesar/p/14998149.html