Majority Element in Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
public class MajorityElementArray { | |
public static void main(String[] args){ | |
Scanner in=new Scanner(System.in); | |
int n=in.nextInt(); | |
int arr[]=new int[n]; | |
for(int i=0;i<n;i++){ | |
arr[i]=in.nextInt(); | |
} | |
Integer v; | |
v = null; | |
int max=0; | |
int count; | |
for(int i=0;i<n;i++){ | |
count=0; | |
if(v!=Integer.valueOf(arr[i])){ | |
for(int j=i+1;j<n;j++){ | |
if(arr[i]==arr[j]){ | |
count++; | |
} | |
} | |
count++; | |
if(count>max){ | |
max=count; | |
v=Integer.valueOf(arr[i]); | |
} | |
} | |
} | |
if(max>1){ | |
System.out.println("element "+v+" occured "+max+" of times"); | |
} | |
else{ | |
System.out.println("No majority element"); | |
} | |
} | |
} |
Comments
Post a Comment