数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。你可以假设数组是非空的,并且给定的数组总是存在多数元素。
剑指 Offer 39. 数组中出现次数超过一半的数字 - 力扣(LeetCode) (leetcode-cn.com)
//用哈希表存储每个数字出现的次数,找出出现次数超过一半的数字
class Solution {
public int majorityElement(int[] nums) {
int len = nums.length;
Map<Integer, Integer> map = new HashMap();
for(int i = 0; i < nums.length; i++){
map.put(nums[i], map.getOrDefault(nums[i],0) + 1);
}
for(Map.Entry<Integer, Integer> entry:map.entrySet()){
if(entry.getValue() > (len / 2)){
return entry.getKey();
}
}
return -1;
}
}
//摩尔投票,遍历数组,当投票数count=0时,令当前数字x是目标数字,当num=x时,count自增1;当num!=x 时,count自减 1,如果数组中一定存在出现次数超过一半的数字,数组遍历完之后的target就是结果
class Solution {
public int majorityElement(int[] nums) {
int target = nums[0];
int count = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] == target){
count++;
}else{
count--;
}
if(count == 0){
target = nums[i+1];
}
}
return target;
}
}