forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain5.cpp
40 lines (30 loc) · 750 Bytes
/
main5.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/// Source : https://leetcode.com/problems/majority-element/description/
/// Author : liuyubobobo
/// Time : 2017-11-14
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
/// Boyer-Moore Voting Algorithm
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {
public:
int majorityElement(vector<int>& nums) {
assert(nums.size() > 0);
int count = 0;
int res = -1;
for(int num: nums){
if(count == 0)
res = num;
count += (res == num) ? 1 : -1;
}
return res;
}
};
int main() {
int nums[1] = {1};
vector<int> vec(nums, nums + 1);
cout << Solution().majorityElement(vec) << endl;
return 0;
}