JZ28 数组中出现次数超过一半的数字
问题描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组[1,2,3,2,2,2,5,4,2]。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。你可以假设数组是非空的,并且给定的数组总是存在多数元素。1<=数组长度<=50000
问题分析
我首先想到的是用hash。先遍历一遍数组,在map中存每个元素出现的次数,然后再遍历一次数组,找出次数超过一半的数字。时间复杂度和空间复杂度都是O(n)。
还可以使用排序,先将数组排序,可能的满足要求的数肯定在数组中间,然后判断一下这个数出现的次数是否超过了数组长度的一半。时间复杂度是O(nlogn),空间复杂度O(1)。
还有一种方法是最优的方法,时间复杂度O(n),空间复杂度O(1)。
思想:如果两个数不相等,就消去这两个数,最坏情况下,每次消去一个众数和一个非众数,那么如果存在众数,最后留下的数肯定是众数。
具体做法:
初始化:候选人num = -1, 候选人的投票次数count = 0
遍历数组,如果count=0, 表示没有候选人,则选取当前数为候选人,++count;
否则,如果count > 0, 表示有候选人,如果当前数=num,则++count,否则–count
直到数组遍历完毕,最后检查num是否为众数
解法一
import java.util.*;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
Map<Integer,Integer> temp=new HashMap<Integer,Integer>();
for(Integer c:array){
if (temp.get(c)!=null){
int val=temp.get(c);
temp.put(c,++val);
}else {
temp.put(c,1);
}
}
for(int i=0;i<array.length;i++){
if(temp.get(array[i])>array.length/2){
return array[i];
}
}
return -1;
}
}
解法二
import java.util.*;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
Arrays.sort(array);
int num=0;
for (int c:array){
if (array[array.length/2]==c){
num++;
}
}
if (num>array.length/2)
return array[array.length/2];
return 0;
}
}
解法三
import java.util.*;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
// 可能的众数
int num=-1;
// 计数
int count=0;
for (int i:array){
if (count==0){
num=i;
++count;
}else {
count=num==i?++count:--count;
}
}
count=0;
for (int i:array){
if (num==i) ++count;
}
if (count>array.length/2) return num;
return 0;
}
}