【leetcode】169(Easy). Majority Element

解题思路:

使用一个map

提交代码:

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

运行结果:
【leetcode】169(Easy). Majority Element