数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2] 输出: 2
方法一:哈希表
时间复杂度和空间复杂度都为On
class Solution {
public int majorityElement(int[] nums) {
int length = nums.length;
Map<Integer, Integer> agrs = new HashMap<>();
for(int i = 0;i < length; i++){
int count = agrs.getOrDefault(nums[i], 0) + 1;
if(count > (nums.length / 2))
return nums[i];
agrs.put(nums[i], count);
}
return -1;
}
}
方法二:排序
因为我们需要找到个数达到2/n的值,所以排序后不管递增还是递减最后都一定是nums[n/2];
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
}
方法三:摩尔投票法
具体解法看此链接剑指 Offer 39. 数组中出现次数超过一半的数字(摩尔投票法,清晰图解) - 数组中出现次数超过一半的数字 - 力扣(LeetCode) (leetcode-cn.com)
class Solution {
public int majorityElement(int[] nums) {
int x = 0;
int vote = 0;
for(int num:nums){
//x = num;
if(vote == 0) x = num;
vote += x==num?1:-1;
}
}
}