LeetCode Solutions
169. Majority Element
Time: $O(n)$ Space: $O(1)$
class Solution {
public:
int majorityElement(vector<int>& nums) {
int ans;
int count = 0;
for (const int num : nums) {
if (count == 0)
ans = num;
count += num == ans ? 1 : -1;
}
return ans;
}
};
class Solution {
public int majorityElement(int[] nums) {
Integer ans = null;
int count = 0;
for (final int num : nums) {
if (count == 0)
ans = num;
count += num == ans ? 1 : -1;
}
return ans;
}
}
class Solution:
def majorityElement(self, nums: List[int]) -> int:
ans = None
count = 0
for num in nums:
if count == 0:
ans = num
count += (1 if num == ans else -1)
return ans