-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMajority_element
More file actions
66 lines (52 loc) · 1.83 KB
/
Majority_element
File metadata and controls
66 lines (52 loc) · 1.83 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
----------------------------------------------------------------------
---------------------- Moore’s Voting Algorithm: ----------------
----------------------------------------------------------------------
** This Method only works when we are given that majority element do exist in the array **
IDEA - Basic idea of the algorithm is that if we cancel out each occurrence of an element e with all
the other elements that are different from e then e will exist till end if it is a majority element.
Time Complexity - O(n)
Space complexity - o(1)
class Solution {
public:
int majorityElement(vector<int>& nums) {
int mx= 0;
int n= nums.size();
int count=1;
for(int i=1;i<n;i++){
if(nums[mx]== nums[i])
count++;
else count--;
if(count == 0){
mx = i;
count = 1;
}
}
return nums[mx];
}
};
---------------------------------------------
---------------------------- OR -------------
---------------------------------------------
# include <bits/stdc++.h>
using namespace std;
int main ()
{
/* Given an array of n elements, find the majority element.
A majority element occurs at least n/2 + 1 times.
If it doesn't exist print -1.
*/
int n=11; // number of elements (indexes 1-11)
//index 0 1 2 3 4 5 6 7 8 9 10 11
int A[]={0,1,1,4,5,1,6,6,1,1,3, 1};
sort (A+1, A+n+1);
// A[n/2+1] can be the majority element
int majorityElement=A[n/2+1];
int nrOccurrences=0;
for (int i=1; i<=n; ++i)
if (A[i]==majorityElement) ++nrOccurrences;
if (nrOccurrences >= n/2 + 1) {
cout<<"The majority element is "<<majorityElement;
cout<<" and it appears "<<nrOccurrences<<" times";
} else cout<<"-1\n";
return 0;
}