热身2---求众数

题目描述:

class Solution {
    public int majorityElement(int[] nums) {
        /*Arrays.sort(nums);
        return nums[nums.length/2];*/
        if(nums.length==1)
            return nums[0];
        HashMap<Integer,Integer> hashMap=new HashMap<>();
        for(int i=0;i<nums.length;i++){
            if(hashMap.containsKey(nums[i])){//包含
                int count=hashMap.get(nums[i]);
                hashMap.put(nums[i],++count);
                if(count>nums.length/2)//超过一半
                    return nums[i];
            }
            else
                hashMap.put(nums[i],1);//第一个
        }
        return 0;
    }
}

 

posted @ 2019-03-04 15:38  本尘  阅读(127)  评论(0)    收藏  举报