题解 | #数组中出现次数超过一半的数字#
数组中出现次数超过一半的数字
http://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163
import java.util.*;
public class Solution {
public int MoreThanHalfNum_Solution(int[] array) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < array.length; i++) {
if (!map.containsKey(array[i])) {
map.put(array[i], 1);
} else {
int newVal = map.get(array[i]);
map.replace(array[i], newVal+1);
}
}
Set<Integer> set = map.keySet();
for (Integer i : set) {
if (map.get(i) >= (array.length + 1) /2 ) {
return i;
}
}
return -1;
}
}