leetcode--Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

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

你可能感兴趣的:(leetcode--Majority Element)