-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path169-Majority-Element.cpp
More file actions
37 lines (30 loc) · 914 Bytes
/
169-Majority-Element.cpp
File metadata and controls
37 lines (30 loc) · 914 Bytes
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
class Solution {
public:
int majorityElement(vector<int>& nums) {
pair<int, int> p;
p.first = nums[0];
p.second = 0;
for(int i=1; i<nums.size(); i++){
if(nums[i] == p.first){
p.second++;
}
else if(p.second == 0){
p.first = nums[i];
}
else{
p.second--;
}
}
return p.first;
}
};
/* 169. Majority-Element.cpp
//////////////////////////////////////////////////
Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times.
You may assume that the majority element always exists in the array.
Input: nums = [2,2,1,1,1,2,2]
Output: 2
https://leetcode.com/problems/majority-element/
//////////////////////////////////////////////////
*/