题目:
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
解题思路: 利用hashMap存储键值对的特性, key记录数字,value记录每个数字出现的次数,具体实现如下:
代码实现:
import java.util.HashMap;
import java.util.Map;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
HashMap<Integer,Integer> hashMap = new HashMap<Integer,Integer>();//创建hashMap存数数据
int i = 0;
int j = 0;
while(i < array.length){
int tmp = array[i];
if(hashMap.containsKey(tmp)){
hashMap.put(tmp, hashMap.get(tmp)+1);
}else{
hashMap.put(tmp, 1);
}
i++;
}
for(Map.Entry<Integer, Integer> entry: hashMap.entrySet())
{
if(entry.getValue() > array.length/2){
j = entry.getKey();
}
}
return j != 0? j:0;
}
}