169. Majority Element
¶
- Time: $O(n)$
- Space: $O(1)$
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 | |
var majorityElement = function(nums) {
let cand = 0, count = 0;
for (const n of nums) {
if (count === 0) cand = n;
count += (n === cand ? 1 : -1);
}
return cand;
};