-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmajority_element_solution.cpp
More file actions
39 lines (31 loc) · 1.09 KB
/
majority_element_solution.cpp
File metadata and controls
39 lines (31 loc) · 1.09 KB
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
/*
Daniel Diaz
LeetCode Problem - Majority Element
- Description:
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.
*/
// - My Solution:
class Solution {
public:
int majorityElement(vector<int>& nums) {
//uses the boyer-moore voting algorithm
int count = 1, candidate = nums[0];
for (int i = 1; i < nums.size(); ++i) {
//if current element is not the same as the candidate, we decrement the count variable by 1
if (nums[i] != candidate) {
--count;
}
//otherwise we just increment it by 1 if they're the same
else {
++count;
}
// if count ever reaches 0, we found a new candidate and increment count by 1
if (!count) {
candidate = nums[i];
++count;
}
}
return candidate;
}
};