数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2
限制:
1 <= 数组长度 <= 50000
方法一:
遍历计数。
使用map。
如果大于数组长度一半了,就返回这个值。
代码:
class Solution {
public int majorityElement(int[] nums) {
// 暴力 遍历 存放到map中。
if (nums.length == 1) return nums[0];
int n = nums.length / 2;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0 ; i < nums.length; i++) {
if (map.containsKey(nums[i])) {
int t = map.get(nums[i]) + 1;
if (t > n) return nums[i];
map.put(nums[i], t);
} else {
map.put(nums[i], 1);
}
}
return -1;
} }
时间复杂度:O(n)
空间复杂度:O(n)
方法二:
排序,然后取中间的那个,就一定是答案。
因为,是结果的那个数字,超过半数了,排序后,一定会再中间的位置上。
代码:
class Solution {
public int majorityElement(int[] nums) {
// 排序 遍历 计数。nlgn lgn
if (nums.length == 1) return nums[0];
Arrays.sort(nums);
int n = nums.length / 2;
return nums[n];
}
}
时间复杂度:O(nlgn)
空间复杂度:O(1)
方法三:
摩尔投票法。
就是让不同的数字相互抵消,抵消之后,记录后面的数字,这样的话,最终留下的(记录的),一定是超过半数的那个数字。因为超过半数的那个数字,把其他的数字抵消掉之后,还会有剩余。
代码:
class Solution {
public int majorityElement(int[] nums) {
// 如果票为0,则记录当前这个元素。即,这俩个数字已经被抵消了,那就抛弃已经被抵消的元素。开始往后接着记录,最终超过一半的数字一定会把所有的其他数字抵消完,然后剩下的就是超过半数的那个数字。
// 摩尔投票:就是不同的数字会抵消,那么剩下的就是多的那个。
int res = 0, vote = 0;
for (int i = 0; i < nums.length; i++) {
if (vote == 0) res = nums[i];
vote += res == nums[i] ? 1 : -1;
}
return res;
}
}
时间复杂度:O(n)
空间复杂度:O(1)