Skip to content

Commit b24591b

Browse files
authored
Add files via upload
This solution uses the Boyer-Moore Voting Algorithm to find the majority element (an element that appears more than n/2 times) in linear time with constant space. The algorithm maintains a count (i) and a candidate (j). It iterates through the array, updating the candidate whenever the count reaches zero. If the current element matches the candidate, the count increases; otherwise, it decreases. At the end of the iteration, the candidate is guaranteed to be the majority element. Time Complexity: O(n) Space Complexity: O(1)
1 parent 55c0aa7 commit b24591b

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

169.Majority Element.cpp

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution {
2+
public:
3+
int majorityElement(vector<int>& nums) {
4+
// i is the count for tracking the majority candidate
5+
int i = 0;
6+
7+
// j is the variable to store the current majority candidate
8+
int j = 0;
9+
10+
// Boyer-Moore Voting Algorithm: This loop determines the majority element
11+
for (int num : nums) {
12+
// If count 'i' becomes 0, assign the current element 'num' as the new candidate
13+
if (i == 0) {
14+
j = num;
15+
}
16+
// If 'num' is the current candidate 'j', increment the count
17+
// Otherwise, decrement the count
18+
i += (num == j) ? 1 : -1;
19+
}
20+
21+
// Return the candidate which is the majority element
22+
return j;
23+
}
24+
};
25+

0 commit comments

Comments
 (0)