Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.
for(n : nums)
cnt = map.get(n)
map.put(n, cnt + 1)
return Max(map.getValues())
public int majorityElement(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
int cnt = map.getOrDefault(num, 0);
map.put(num, cnt + 1);
}
return map.entrySet().stream()
.max(Comparator.comparingInt(Map.Entry::getValue))
.orElseThrow(RuntimeException::new)
.getKey();
}
내 풀이가 통과를 하긴 했지만 출제자가 의도한 풀이가 아닌 것 같다
public int majorityElement(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
return nums[n/2];
}