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.
用hashmap即可搞定。
public static int majorityElement(int[] nums) {
int count;
int len = nums.length / 2;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
if (map.get(nums[i]) != null) {
count = map.get(nums[i]);
count++;
map.put(nums[i], count);
} else {
map.put(nums[i], 1);
}
}
Iterator it = map.keySet().iterator();
while (it.hasNext()) {
int key = (int) it.next();
if (map.get(key) > len) {
return key;
}
}
return -1;
}
本文介绍了一种使用HashMap来解决数组中多数元素查找问题的方法。通过遍历数组并利用HashMap记录每个元素出现的次数,最终找到出现次数超过数组长度一半的元素。

被折叠的 条评论
为什么被折叠?



