Majority Element
Leetcode https://leetcode.cn/problems/majority-element/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int majorityElement(int[] nums) {
int candidate = nums[0];
int counter = 0;
for (int num : nums) {
if (counter == 0) {
candidate = num;
counter = 1;
continue;
}
if (candidate == num) {
counter++;
} else {
counter--;
}
}
return candidate;
}
}
Complexity
- Time = O(n)
- Space = O(1)
This post is licensed under CC BY 4.0 by the author.