剑指 Offer 39. 数组中出现次数超过一半的数字
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。你可以假设数组是非空的,并且给定的数组总是存在多数元素。
方法一:哈希表统计法
public static int majorityElement(int[] nums) {
int size = nums.length;
HashMap<Integer,Integer> map = new HashMap();
for(int i = 0; i < size; i++){
int count = 1;
for(int j = i+1; j < size; j++){
if(nums[i] == nums[j] ){
count++;
}
}
map.put(count,nums[i]);
}
Object[] objects = map.keySet().toArray();
Arrays.sort(objects);
return map.get(objects[objects.length -1]);
}
方法二:数组排序法
public static int majorityElementThree(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
方法三:摩尔投票法
public static int majorityElementTwo(int[] nums) {
int votes = 0;
int x = 0;
for(int i : nums){
if(votes ==0)x = i;
votes += x == i ? 1 : -1;
}
//加判断是否超过一半的数量
int count = 0;
for(int num : nums){
if(num == x)count++;
}
return count > nums.length/2 ? x:0;
}