解题思路:将出现的key和key的次数放到map里,然后遍历map,当map的value超过数组的一半,把key输出即可
import java.util.*;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int size = array.length;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < array.length; i++) {
if (map.containsKey(array[i])) {
map.put(array[i], map.get(array[i]) + 1);
} else {
map.put(array[i], 1);
}
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() > size / 2) {
return entry.getKey();
}
}
return -1;
}
}
解法二:因为题目说必有解,那么出现超过一半的数字一定在排序后中间的位置
import java.util.*;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int size = array.length;
Arrays.sort(array);
return array[size / 2];
}
}