-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMajorityElement.java
More file actions
36 lines (35 loc) · 884 Bytes
/
MajorityElement.java
File metadata and controls
36 lines (35 loc) · 884 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
package Searching;
/**
* @author Vishal Singh */
public class MajorityElement{
static int findMajorityElement(int[] arr){
int n = arr.length;
int res = 0;
int count = 1;
for (int i = 1; i < n; i++) {
if(arr[i] == arr[res]){
count++;
}
else {
count--;
}
if (count == 0){
res = i;
count = 1;
}
}
count = 0;
for (int i = 0; i < n; i++) {
if (arr[res] == arr[i])
count++;
}
if (count<=n/2)
res = -1;
return res;
}
public static void main(String[] args) {
int[] arr = {8,7,6,8,6,6,6,6};
int index = findMajorityElement(arr);
System.out.println("Index: "+index+" Element: "+ arr[index]);
}
}