「LeetCode」众数的计算(JAVA实现)

众数

问题描述

给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在众数。

实现思路

众数定义:是一组数据中出现次数最多的数值,叫众数

利用Map记录数字出现的次数,超过总数量的一半即为众数

实现代码

class Solution {
    public int majorityElement(int[] nums) {
        Integer majorityElement = null;
        Map<Integer, Integer> map = new HashMap<>();
        for (Integer n : nums){
            Integer count = map.get(n);
            if(count == null){
                count = 1;
            }else{
                count ++;
            }
            map.put(n,count);
            
            if(count > nums.length/2){
                majorityElement = n;
                break;
            }
        }
        return majorityElement;
    }
}
posted @ 2019-04-26 00:34  张金麒  阅读(1277)  评论(0编辑  收藏  举报