-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday28.cpp
More file actions
44 lines (38 loc) · 982 Bytes
/
day28.cpp
File metadata and controls
44 lines (38 loc) · 982 Bytes
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
#include<bits/stdc++.h>
using namespace std;
// Find majority element in an array (Boyer–Moore majority vote algorithm)
/* Given an array of integers containing duplicates, return the majority element
in an array if present. A majority element appears more than n/2 times where n is
the size of the array. */
//testing
main(){
int n,i,majGuess,t;
cin>>t;
while(t--){
cin>>n;
vector<int>arr(n);
for(i=0;i<n;i++){
cin>>arr[i];
}
majGuess = arr[0];
int count=0;
for(i=0;i<n;i++){
if(count==0)
majGuess = arr[i];
if(arr[i]==majGuess)
count++;
else{
count--;
}
}
int k=0;
for(i=0;i<n;i++){
if(arr[i]==majGuess)
k++;
}
if(k>n/2)
cout<<majGuess<<endl;
else
cout<<"NO Majority Element"<<endl;
}
}