-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path169-Majority-Element.cpp
61 lines (56 loc) · 1.77 KB
/
169-Majority-Element.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/// Author : Vicen-te
/// Date : 10/05/2023 (MM-DD-YYYY)
/**
* 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.
*
* Ex1.
* Input: nums = [3,2,3]
* Output: 3
* Ex2.
* Input: nums = [3,2,3]
* Output: 2
*
* Follow-up: Could you solve the problem in linear time and in O(1) space?
*
* Algorithm:
* We will use the Boyer-Moore Voting Algorithm to efficiently find the majority element in a
* given vector.
*
* The algorithm initializes two variables: 'count' to keep track of the current element's
* count and 'candidate' to store the majority candidate.
*
* It iterates through the vector, and for each element, it performs the following actions:
* - If 'count' is zero, it sets 'candidate' to the current element (designating it as the new
* majority candidate).
* - If the current element matches 'candidate,' it increments 'count.'
* - If the current element differs from 'candidate,' it decrements 'count.'
*
* By the end of the loop, 'candidate' contains the majority element.
*
* Time Complexity: O(N)
* Space Complexity: O(1)
*/
class Solution {
public:
int majorityElement(vector<int>& nums) {
int count = 0;
int candidate = INT_MIN;
for (int& num : nums)
{
if (count == 0){
candidate = num;
}
if(num == candidate ){
++count;
}
else{
--count;
}
}
return candidate;
}
};