-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDay6.cpp
43 lines (41 loc) · 860 Bytes
/
Day6.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
/*
Author: Aryan Yadav
Majority Element
Complexity: O(n)
Algorithm: NA
Difficulty: Easy
*/
class Solution
{
public:
int majorityElement(vector<int> &nums)
{
sort(nums.begin(), nums.end());
int k = floor(nums.size() / 2);
int cnt = 0;
int ans;
int prev = nums[0];
for (int i = 1; i < nums.size(); i++)
{
if (nums[i] == prev)
{
cnt++;
if (cnt == k)
{
ans = nums[i];
break;
}
}
else
{
prev = nums[i];
cnt = 0;
}
}
if (nums.size() == 1)
{
ans = nums[0];
}
return ans;
}
};