Closed congr closed 5 years ago
Time : O(N), Space : O(N)
class Solution {
public int majorityElement(int[] nums) {
Map<Integer, Integer> map = new HashMap();
for (int n : nums) {
int cnt = map.merge(n, 1, Integer::sum);
if (cnt > nums.length/2)
return n;
}
return 0;
}
}
Shortest code
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
}
https://leetcode.com/problems/majority-element/