https://leetcode-cn.com/problems/majority-element/
给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在众数。
示例 1:
输入: [3,2,3]
输出: 3
示例 2:
输入: [2,2,1,1,1,2,2]
输出: 2
参考:https://leetcode-cn.com/problems/majority-element/solution/qiu-zhong-shu-by-leetcode-2/
暴力法
public int majorityElement(int[] nums) {
int mCount = nums.length / 2;
for (int num : nums) {
int count = 0;
for (int elem : nums) {
if (num == elem) {
count++;
}
}
if (count > mCount) {
return num;
}
}
return -1;
}
时间复杂度:O(n^2)
空间复杂度:O(1)O(1)
哈希
public int majorityElement(int[] nums) {
int mCount = nums.length / 2;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int num : nums) {
if (!map.containsKey(num)) {
map.put(num, 1);
} else {
map.put(num, map.get(num) + 1);
}
}
for (int elem : nums) {
int count = map.get(elem);
if (count > mCount) {
return elem;
}
}
return -1;
}
可以对上面的代码简化下:
public int majorityElement(int[] nums) {
int mCount = nums.length / 2;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int num : nums) {
int count = map.getOrDefault(num, 0) + 1;
map.put(num, count);
if(count > mCount) {
return num;
}
}
return -1;
}
时间复杂度:O(n)
空间复杂度:O(n)
摩尔投票法
/**
* 如果我们把众数记为 +1 ,把其他数记为 -1 , 将它们全部加起来,显然和大于 0 ,从结果本身我们可以看出众数比其他数多。
*/
public int majorityElement(int[] nums) {
int count = 0;
Integer candidate = null;
for (int num : nums) {
if (count == 0) {// 之前选择的众数并不是真正的众数,重新设置众数
candidate = num;
}
count += (num == candidate) ? 1 : -1;// 是众数,众数的个数+1,否则就-1
}
return candidate;
}