剑指Offer_#39_数组中出现次数超过一半的数字
Contents
题目
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2
限制:
1 <= 数组长度 <= 50000
解答
解法1:HashMap统计数字出现次数
class Solution {
public int majorityElement(int[] nums) {
HashMap<Integer,Integer> map = new HashMap<>();
for(int i = 0;i <= nums.length - 1;i++){
//第一次遇到某个数字,加入map
if(!map.containsKey(nums[i])) map.put(nums[i],1);
//第二次及以后遇到,次数加1
else map.put(nums[i], map.get(nums[i]) + 1);
//超过一半指的是上取整还是下取整?
// if(map.get(nums[i]) > nums.length / 2) return nums[i];
//用乘法写可以解决上述问题
if(map.get(nums[i]) * 2 > nums.length) return nums[i];
}
//没有找到符合要求的数字,就返回-1
return -1;
}
}
解法2:排序
因为题目条件说了,必然会有众数。所以可以先排序,在排序后的数组当中,众数必然在数组中间位置。
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length / 2];
}
}
解法3:摩尔投票法
看到一个很形象的解释:
可以理解成混战极限一换一,不同的两者一旦遇见就同归于尽,最后活下来的值都是相同的,即要求的结果。
class Solution {
public int majorityElement(int[] nums) {
//当前假设的众数是major
int major = 0;
//计数,遍历到的数字是当前众数,就加1,否则减1
int count = 0;
for(int i = 0;i <= nums.length - 1;i++){
//count为0,缩减范围,从nums[i]重新开始计数,major设置为nums[i]
if(count == 0) major = nums[i];
count += (major == nums[i])? 1 : -1;
}
return major;
}
}