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.
解法一
Moore的主页上有这个算法的介绍:A Linear Time Majority Vote Algorithm 和这个算法的一个简单示例演示:演示链接。
主要思想为:每次都找出一对不同的元素,从数组中删掉,直到数组为空或只有一种元素。 不难证明,如果存在元素e出现频率超过半数,那么数组中最后剩下的就只有e。
public class Solution {
public int majorityElement(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int major = nums[0];
int count = 1;
for (int i = 1; i < nums.length; i++) {
if (count == 0) {
major = nums[i];
count++;
} else if (nums[i] == major) {
count++;
} else {
count--;
}
}
return major;
}
}
解法二
元素的个数存在map中。
public class Solution {
public int majorityElement(int[] nums) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int ret = 0;
for (int num : nums) {
if (!map.containsKey(num)) {
map.put(num, 1);
} else {
map.put(num, map.get(num) + 1);
}
if (map.get(num) > nums.length / 2) {
ret = num;
break;
}
}
return ret;
}
}
解法三
排序,取中间的元素
public class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
}