Getting index of majority element GFG
public class MajorityElement {
// Efficient solution
public static int getIndexOfMajorityElement(int[] arr) {
int n = arr.length;
int res = 0; int count = 1;
for(int i = 1; i < n; i++) {
if(arr[res] == arr[i]) {
count++;
}
else count--;
if(count == 0) {
count = 1;
res = i;
}
}
count = 0;
for(int i = 0; i < n; i++) {
if(arr[res] == arr[i]){
count++;
}
}
if(count <= n / 2){
return -1;
}
return res;
}
// Printing the index of majority element
public static int getIndex(int[] arr) {
int n = arr.length;
for(int i = 0; i < n; i++) {
int count = 1;
for(int j = i + 1; j < n; j++) {
if(arr[i] == arr[j]) {
count++;
}
}
if(count > n / 2){
return i;
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = {8,8,6,6,6,4,6};
System.out.println(getIndexOfMajorityElement(arr));
}
}
Comments
Post a Comment