题目
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.
答案1
第一反应用HashMap,时间复杂度O(n),空间复杂度O(n),不推荐。
public int majorityElement(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i : nums) {
if (map.containsKey(i)) map.put(i, map.get(i) + 1);
else map.put(i, 1);
}
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
if ((int) entry.getValue() > nums.length / 2) return (int) entry.getKey();
}
return 0;
}
答案2
排序后边遍历边计数,又出现次数超过 n / 2
的就return,时间复杂度O(nlogn),空间复杂度O(1)。
public int majorityElement(int[] nums) {
Arrays.sort(nums);
int times = 1;
for (int i = 0; i < nums.length - 1; i++){
if (nums[i + 1] == nums[i]) {
times++;
if (times > nums.length / 2) return nums[i];
} else times = 1;
}
return nums[0];
}
答案3
如果出现次数超过 n / 2
,则第 n / 2
项一定是目标数字。
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}