-
Notifications
You must be signed in to change notification settings - Fork 62
/
MajorityElement.cpp
93 lines (65 loc) · 1.6 KB
/
MajorityElement.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
Source: https://leetcode.com/problems/majority-element/
Approach 1 (using extra space by taking map)
Time: O(n), where n is the length of the given vector(nums)
Space: O(n), map is required to store the frequency of each element
*/
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int, int> map;
int majorityElement = 0;
int halfSize = nums.size() >> 1;
for(int num : nums) {
if(++map[num] > halfSize) {
majorityElement = num;
break;
}
}
return majorityElement;
}
};
/*
Approach 2 (More optimized than approach 1 without using map)
Time: O(n), where n is the length of the given vector(nums)
Space: O(1), in-place
*/
class Solution {
public:
int majorityElement(vector<int>& nums) {
int majorityElement = nums[0];
int count = 1;
int size = nums.size();
for(int i = 1; i < size; ++i) {
if(count == 0) {
majorityElement = nums[i];
}
count += (nums[i] == majorityElement) ? 1 : -1;
}
return majorityElement;
}
};
/*
Slight modification to make it more optimized than approach 2
Time: O(n), where n is the length of the given vector(nums)
Space: O(1), in-place
*/
class Solution {
public:
int majorityElement(vector<int>& nums) {
int majorityElement = nums[0];
int count = 1;
int size = nums.size();
for(int i = 1; i < size; ++i) {
if(count == 0) {
majorityElement = nums[i];
count = 1;
} else if(nums[i] != majorityElement) {
--count;
} else {
++count;
}
}
return majorityElement;
}
};