169. 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.
给定一个数组,找这个数组中的主元素,主元素是元素出现次数大于⌊ n/2 ⌋的元素。 假设给定的数组非空,主元素都存在。
1 public int majorityElement(int[] nums) { 2 Map<Integer, Integer> numberMap = new HashMap<>(); 3 for (int i = 0; i < nums.length; i++) { 4 numberMap.put(nums[i], numberMap.getOrDefault(nums[i], 0)+1); 5 } 6 int level = (nums.length+1)/2; 7 for (Map.Entry<Integer, Integer> e : numberMap.entrySet()) { 8 if (e.getValue() >= level) { 9 return e.getKey(); 10 } 11 } 12 return Integer.MIN_VALUE; 13 }