数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2
限制:
1 <= 数组长度 <= 50000
哈希方法
应掌握 getOrDefault() containKey()等方法的使用
class Solution {
public int majorityElement(int[] nums) {
HashMap<Integer,Integer> hash=new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++) {
hash.put(nums[i],hash.getOrDefault(nums[i],0)+1);
if(hash.get(nums[i])>nums.length/2)//超过一般时,返回
return nums[i];
}
return 0;
}
}
使用排序
因为数组中必然存在一个数字的个数超过数组长度的一半,这样,我们可以先对该数组进行排序,排序之后数组中间位置的数字必然是超出数组一半的数字。
代码为:
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length >> 1];
}