题目描述:
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
代码:
import java.util.HashMap;
import java.util.Map;
/**
* 题目描述
* 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。
* 由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.MoreThanHalfNum_Solution(new int[]{1, 2, 3, 2, 2, 2, 5, 4, 2}));
}
public int MoreThanHalfNum_Solution(int [] array) {
if(array == null || array.length == 0){
return 0;
}
Map<Integer,Integer> map = new HashMap<>();
for (int ints : array) {
Integer integer = map.get(ints);
if(integer != null){
integer++;
} else {
integer = 1;
}
map.put(ints,integer);
}
int size;
if(array.length % 2 == 0){
size = array.length / 2;
} else {
size = array.length / 2;
}
for (Integer ints : map.keySet()) {
if(map.get(ints) > size){
return ints;
}
}
return 0;
}
}