1.描述:
给定一个大小 n 数组nums ,返回大多数元素。大多数元素是指在数组中出现的次数 大于⌊ n/2 ⌋的元素。
你可以假设数组是非空的,给定的数组总是有大多数元素。
示例1:
输入:nums = [3,2,3]
输出:3
示例2:
输入:nums = [2,2,1,1,2]
输出:2
2.实现代码:
class Solution { private Map<Integer, Integer> countNums(int[] nums) { Map<Integer, Integer> counts = new HashMap<Integer, Integer>(); for (int num : nums) { if (!counts.containsKey(num)) { counts.put(num, 1); } else { counts.put(num, counts.get(num) + 1); } } return counts; } public int majorityElement(int[] nums) { Map<Integer, Integer> counts = countNums(nums); Map.Entry<Integer, Integer> majorityEntry = null; for (Map.Entry<Integer, Integer> entry : counts.entrySet()) { if (majorityEntry == null || entry.getValue() > majorityEntry.getValue()) { majorityEntry = entry; } } return majorityEntry.getKey(); }}