Skip to content

Commit f33fb1a

Browse files
authored
Update majority-element.cpp
1 parent 45cb523 commit f33fb1a

File tree

1 file changed

+15
-11
lines changed

1 file changed

+15
-11
lines changed

C++/majority-element.cpp

+15-11
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,21 @@
44
class Solution {
55
public:
66
int majorityElement(vector<int>& nums) {
7-
int result = 0, cnt = 0;
8-
for (const auto& x : nums) {
9-
if (cnt == 0) {
10-
result = x;
7+
const auto& boyer_moore_majority_vote = [&]() {
8+
int result = 0, cnt = 0;
9+
for (const auto& x : nums) {
10+
if (cnt == 0) {
11+
result = x;
12+
}
13+
if (x == result) {
14+
++cnt;
15+
} else {
16+
--cnt;
17+
}
1118
}
12-
if (x == result) {
13-
++cnt;
14-
} else {
15-
--cnt;
16-
}
17-
}
18-
return result;
19+
return result;
20+
};
21+
22+
return boyer_moore_majority_vote();
1923
}
2024
};

0 commit comments

Comments
 (0)