题目:数组中出现超过一半的数字
思路:哈希
代码:
import java.util.*;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
Map<Integer, Integer> map = new HashMap<>();
int n = array.length / 2;
for (int num : array) {
int temp = map.getOrDefault(num, 0) + 1;
if (temp > n) {
return num;
}
map.put(num, temp);
}
return 0;
}
}