leetcode刷题8

今天刷的题是LeetCode第169题,求众数。我采用的方法是:hashmap的方式。具体代码如下:

class Solution {
    public int majorityElement(int[] nums) {
        HashMap<Integer,Integer> map=new HashMap<>();
        for (int i = 0; i <nums.length ; i++) {
            if (map.containsKey(nums[i])){
                map.put(nums[i],map.get(nums[i])+1);
            }else {
                map.put(nums[i],1);
            }            
        }
        for (int i = 0; i <nums.length ; i++) {
            if (map.get(nums[i])>nums.length/2){
                return nums[i];
            }
        }
        return -1;
    }
}

 

posted @ 2019-08-12 17:28  刘云生  阅读(126)  评论(0编辑  收藏  举报