Skip to content

Commit a284f0c

Browse files
authored
Solution of Majority element problem.cpp
1 parent 23fad4d commit a284f0c

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

Majority element.cpp

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
public:
3+
int majorityElement(vector<int>& nums) {
4+
int major_element = nums[0];
5+
int count = 1;
6+
7+
for (int i = 1; i < nums.size(); ++i) {
8+
if (nums[i] == major_element) {
9+
count++;
10+
} else {
11+
count--;
12+
if (count == 0) {
13+
major_element = nums[i];
14+
count = 1;
15+
}
16+
}
17+
}
18+
19+
return major_element;
20+
}
21+
};

0 commit comments

Comments
 (0)