具体实现:
class Solution {
public int majorityElement(int[] nums) {
Map<Integer, Integer> m = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (!m.containsKey(nums[i])) {
m.put(nums[i],1);
} else {
m.put(nums[i],m.get(nums[i])+1);
}
}
Map<Integer, Integer> result = new LinkedHashMap<>();
m.entrySet().stream()
.sorted(Map.Entry.<Integer, Integer>comparingByValue().reversed())
.forEachOrdered(x -> result.put(x.getKey(), x.getValue()));
return (int) result.keySet().toArray()[0];
}
}