-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path169.majority-element.cpp
More file actions
84 lines (84 loc) · 1.52 KB
/
Copy path169.majority-element.cpp
File metadata and controls
84 lines (84 loc) · 1.52 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
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
class Solution
{ // bruteforce solution O(n^2)
public:
int majorityElement(vector<int> &nums)
{
int n = nums.size();
for (int i = 0; i < n; i++)
{
int cnt = 0;
for (int j = 0; j < n; j++)
{
if (nums[i] == nums[j])
cnt++;
}
if (cnt > n / 2)
return nums[i];
}
return n;
}
};
class Solution
{ // better solution
public:
int majorityElement(vector<int> &nums)
{
int n = nums.size();
unordered_map<int, int> mp;
for (int i = 0; i < n; i++)
{
mp[nums[i]]++;
}
for (auto it : mp)
{
if (it.second > (n / 2))
return it.first;
}
return n;
}
};
class Solution
{ // optimal solution O(NlogN)
public:
int majorityElement(vector<int> &nums)
{
int n = nums.size();
sort(nums.begin(), nums.end());
// majority element will always occupy the middle index
return nums[n / 2];
}
};
class Solution
// Moore's Voting Algorithm O(n)
{ // optimal solution
public:
int majorityElement(vector<int> &nums)
{
int n = nums.size();
int cnt = 0;
int el;
for (int i = 0; i < n; i++)
{
if (cnt == 0)
{
cnt = 1;
el = nums[i];
}
else if (nums[i] == el)
cnt++;
else
cnt--;
}
// if majority element doesnot always exist
// int cnt1 = 0l;
// for (int i = 0; i < n; i++)
// {
// if (nums[i] == el)
// cnt1++;
// }
// if (cn1 > (n / 2))
// return el;
// return -1;
return el;
}
};