
[LeetCode] 169. Majority Element
題目說明
給定大小為 n 的數組 nums,返回主要元素。
主要元素是指出現次數超過 ⌊n / 2⌋ 次的元素。
你可以假設該主要元素一定存在於數組中。
題目連結:LeetCode - Majority Element
解法: 使用 HashMap
這裡我使用 HashMap 紀錄哪個數字出現的次數最多
- 宣告 HashMap
- nums 走訪每個元素,並且將元素記錄在 HashMap
- 最後找出次數最多的數字
最後的 Code 如下:
public int majorityElement(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
for (Map.Entry<Integer, Integer> mapEntry : map.entrySet()) {
if (mapEntry.getValue() > nums.length / 2) {
return mapEntry.getKey();
}
}
return -1;
}