Majority Element - LeetCode
class Solution {
public int majorityElement(int[] nums) {
Map<Integer, Integer> m = new HashMap<>();
for (int n: nums){
m.put(n, m.getOrDefault(n, 0) + 1);
}
for (int k: m.keySet()){
if (m.get(k) > nums.length/2) return k;
}
return 0;
}
}
class Solution {
public int majorityElement(int[] nums) {
int c = 0, m = 0;
for (int n: nums){
if (c == 0) m = n;
if (n == m) c++; // notice it's not else if here
else c--;
}
return m;
}
}
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
}
class Solution:
def majorityElement(self, nums: List[int]) -> int:
majorEle = nums[0]
count = 1
for i in range(1, len(nums)):
if count == 0: majorEle = nums[i]
if nums[i] == majorEle: count += 1
else: count -= 1
return majorEle
class Solution:
def majorityElement(self, nums: List[int]) -> int:
return collections.Counter(nums).most_common(1)[0][0]
class Solution:
def majorityElement(self, nums: List[int]) -> int:
nums.sort()
return nums[len(nums)//2]
var majorityElement = function(nums) {
let count = res = 0;
for (let v of nums){
if(count == 0) res = v;
if (res == v) count++;
else count--;
}
return res;
};