int[] a = new int[10]{1,2,3,4,5,6,7,7,7,7};
how can I write a method and return 7?
I want to keep it native without the help of lists, maps or other helpers. Only arrays[].
int[] a = new int[10]{1,2,3,4,5,6,7,7,7,7};
how can I write a method and return 7?
I want to keep it native without the help of lists, maps or other helpers. Only arrays[].
public int getPopularElement(int[] a) { int count = 1, tempCount; int popular = a[0]; int temp = 0; for (int i = 0; i count) { popular = temp; count = tempCount; } } return popular; }
Try this answer. First, the data:
int[] a = {1,2,3,4,5,6,7,7,7,7};
Here, we build a map counting the number of times each number appears:
Map map = new HashMap(); for (int i : a) { Integer count = map.get(i); map.put(i, count != null ? count+1 : 0); }
Now, we find the number with the maximum frequency and return it:
Integer popular = Collections.max(map.entrySet(), new Comparator>() { @Override public int compare(Entry o1, Entry o2) { return o1.getValue().compareTo(o2.getValue()); } }).getKey();
As you can see, the most popular number is seven:
System.out.println(popular); > 7
EDIT
Here's my answer without using maps, lists, etc. and using only arrays; although I'm sorting the array in-place. It's O(n log n) complexity, better than the O(n^2) accepted solution.
public int findPopular(int[] a) { if (a == null || a.length == 0) return 0; Arrays.sort(a); int previous = a[0]; int popular = a[0]; int count = 1; int maxCount = 1; for (int i = 1; i maxCount) { popular = a[i-1]; maxCount = count; } previous = a[i]; count = 1; } } return count > maxCount ? a[a.length-1] : popular; }
Assuming your array is sorted (like the one you posted) you could simply iterate over the array and count the longest segment of elements, it's something like @narek.gevorgyan's post but without the awfully big array, and it uses the same amount of memory regardless of the array's size:
private static int getMostPopularElement(int[] a){ int counter = 0, curr, maxvalue, maxcounter = -1; maxvalue = curr = a[0]; for (int e : a){ if (curr == e){ counter++; } else { if (counter > maxcounter){ maxcounter = counter; maxvalue = curr; } counter = 0; curr = e; } } if (counter > maxcounter){ maxvalue = curr; } return maxvalue; } public static void main(String[] args) { System.out.println(getMostPopularElement(new int[]{1,2,3,4,5,6,7,7,7,7})); }
If the array is not sorted, sort it with Arrays.sort(a);
this one without maps
public class MAIN { public static void main(String[] args) { int[] a = new int[]{1,2,3,4,5,6,7,7,7,7}; System.out.println(getMostPopularElement(a)); } private static int getMostPopularElement(int[] a){ int maxElementIndex = getArrayMaximumElementIndex(a); int[] b= new int[a[maxElementIndex]+1]; for(int i = 0; i=a[maxElementIndex]){ maxElementIndex = i; } } return maxElementIndex; } }
You only have to change some code if your array can have elements which are . And this algorithm is useful when your array items are not big numbers.
If you don't want to use a map, then just follow these steps:
Arrays.sort()
)How about this one
Array elements vallue should be less than the array length.
public void findCounts(int[] arr, int n) { int i = 0; while (i 0) { arr[i] = arr[elementIndex]; arr[elementIndex] = -1; } else { arr[elementIndex]--; arr[i] = 0; i++; } } Console.WriteLine("Below are counts of all elements"); for (int j = 0; j " + Math.Abs(arr[j])); }
Time complexity of this will be O(N) and space complexity will be O(1).
Using Java 8 Streams
int data[] = {1,5,7,4,6,2,0,1,3,2,2}; Map count = Arrays.stream(data).boxed() .collect(Collectors.groupingBy(Function.identity(), counting())); int max = count.entrySet().stream().max((first,second)->{ return (int)(first.getValue() - second.getValue()); }).get().getKey(); System.out.println(max);
Explanation
We convert the int[] data
array to boxed Integer Stream. Then we collect by groupingBy on the element and use a secondary counting collector for counting after the groupBy.
Finally we sort the map of element -> count based on count again by using a stream and lambda comparator.
Seems like you are looking for the Mode value (Statistical Mode) , have a look at Apache's Docs for Statistical functions.
import java.util.Scanner; public class Mostrepeatednumber { public static void main(String args[]) { int most = 0; int temp=0; int count=0,tempcount; Scanner in=new Scanner(System.in); System.out.println("Enter any number"); int n=in.nextInt(); int arr[]=new int[n]; System.out.print("Enter array value:"); for(int i=0;i
package frequent; import java.util.HashMap; import java.util.Map; public class Frequent_number { //Find the most frequent integer in an array public static void main(String[] args) { int arr[]= {1,2,3,4,3,2,2,3,3}; System.out.println(getFrequent(arr)); System.out.println(getFrequentBySorting(arr)); } //Using Map , TC: O(n) SC: O(n) static public int getFrequent(int arr[]){ int ans=0; Map m = new HashMap(); for(int i:arr){ if(m.containsKey(i)){ m.put(i, m.get(i)+1); }else{ m.put(i, 1); } } int maxVal=0; for(Integer in: m.keySet()){ if(m.get(in)>maxVal){ ans=in; maxVal = m.get(in); } } return ans; } //Sort the array and then find it TC: O(nlogn) SC: O(1) public static int getFrequentBySorting(int arr[]){ int current=arr[0]; int ansCount=0; int tempCount=0; int ans=current; for(int i:arr){ if(i==current){ tempCount++; } if(tempCount>ansCount){ ansCount=tempCount; ans=i; } current=i; } return ans; } }
Mine Linear O(N)
Using map to save all the differents elements found in the array and saving the number of times ocurred, then just getting the max from the map.
import java.util.HashMap; import java.util.Map; public class MosftOftenNumber { // for O(N) + map O(1) = O(N) public static int mostOftenNumber(int[] a) { Map m = new HashMap(); int max = 0; int element = 0; for(int i=0; imax){ max = (int) m.get(a[i]); element = a[i]; } } return element; } public static void main(String args[]) { // int[] array = {1,1,2,1,1}; // int[] array = {2,2,1,2,2}; int[] array = {2,2,1,3,3,5,5,6,6,7,7,9,9,10,10,10,10,11,12,13,14,15,15,1,15,15,1,15,15}; System.out.println(mostOftenNumber(array)); } }
Best approach will be using map where key will be element and value will be the count of each element. Along with that keep an array of size that will contain the index of most popular element . Populate this array while map construction itself so that we don't have to iterate through map again.
Approach 2:-
If someone want to go with two loop, here is the improvisation from accepted answer where we don't have to start second loop from one every time
public class TestPopularElements { public static int getPopularElement(int[] a) { int count = 1, tempCount; int popular = a[0]; int temp = 0; for (int i = 0; i count) { popular = temp; count = tempCount; } } return popular; } public static void main(String[] args) { int a[] = new int[] {1,2,3,4,5,6,2,7,7,7}; System.out.println("count is " +getPopularElement(a)); } }
Assuming your int array is sorted, i would do...
int count = 0, occur = 0, high = 0, a; for (a = 1; a occur) { occur = count; high = n[a]; } } else { count = 0; } } System.out.println("highest occurence = " + high);
public static void main(String[] args) { int[] myArray = {1,5,4,4,22,4,9,4,4,8}; Map arrayCounts = new HashMap(); Integer popularCount = 0; Integer popularValue = 0; for(int i = 0; i popularCount) { popularCount = count; popularValue = myArray[i]; } } System.out.println(popularValue + " --> " + popularCount); }
below code can be put inside a main method
// TODO Auto-generated method stub Integer[] a = { 11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 1, 2, 2, 2, 2, 3, 4, 2 }; List list = new ArrayList(Arrays.asList(a)); Set set = new HashSet(list); int highestSeq = 0; int seq = 0; for (int i : set) { int tempCount = 0; for (int l : list) { if (i == l) { tempCount = tempCount + 1; } if (tempCount > highestSeq) { highestSeq = tempCount; seq = i; } } } System.out.println("highest sequence is " + seq + " repeated for " + highestSeq);
public class MostFrequentIntegerInAnArray { public static void main(String[] args) { int[] items = new int[]{2,1,43,1,6,73,5,4,65,1,3,6,1,1}; System.out.println("Most common item = "+getMostFrequentInt(items)); } //Time Complexity = O(N) //Space Complexity = O(N) public static int getMostFrequentInt(int[] items){ Map itemsMap = new HashMap(items.length); for(int item : items){ if(!itemsMap.containsKey(item)) itemsMap.put(item, 1); else itemsMap.put(item, itemsMap.get(item)+1); } int maxCount = Integer.MIN_VALUE; for(Entry entry : itemsMap.entrySet()){ if(entry.getValue() > maxCount) maxCount = entry.getValue(); } return maxCount; } }
int largest = 0; int k = 0; for (int i = 0; i largest) { k = a[i]; largest = count; } }
So here n
is the length of the array, and a[]
is your array.
First, take the first element and check how many times it is repeated and increase the counter (count
) as to see how many times it occurs. Check if this maximum number of times that a number has so far occurred if yes, then change the largest variable (to store the maximum number of repetitions) and if you would like to store the variable as well, you can do so in another variable (here k
).
I know this isn't the fastest, but definitely, the easiest way to understand
public class MostFrequentNumber { public MostFrequentNumber() { } int frequentNumber(List list){ int popular = 0; int holder = 0; for(Integer number: list) { int freq = Collections.frequency(list,number); if(holder list = new ArrayList(); for(Integer num : numbers){ list.add(num); } MostFrequentNumber mostFrequentNumber = new MostFrequentNumber(); System.out.println(mostFrequentNumber.frequentNumber(list)); } }
I hope this helps. public class Ideone { public static void main(String[] args) throws java.lang.Exception {
int[] a = {1,2,3,4,5,6,7,7,7}; int len = a.length; System.out.println(len); for (int i = 0; i
}
You can count the occurrences of the different numbers, then look for the highest one. This is an example that uses a Map, but could relatively easily be adapted to native arrays.
Second largest element: Let us take example : [1,5,4,2,3] in this case, Second largest element will be 4.
Sort the Array in descending order, once the sort done output will be A = [5,4,3,2,1]
Get the Second Largest Element from the sorted array Using Index 1. A[1] -> Which will give the Second largest element 4.
private static int getMostOccuringElement(int[] A) { Map occuringMap = new HashMap();
//count occurences for (int i = 0; i entry : occuringMap.entrySet()) { if (entry.getValue() > max) { max = entry.getValue(); element = entry.getKey(); } } return element; }
This is the wrong syntax. When you create an anonymous array you MUST NOT give its size.
When you write the following code :
new int[] {1,23,4,4,5,5,5};
You are here creating an anonymous int array whose size will be determined by the number of values that you provide in the curly braces.
You can assign this a reference as you have done, but this will be the correct syntax for the same :-
int[] a = new int[]{1,2,3,4,5,6,7,7,7,7};
Now, just Sysout with proper index position:
System.out.println(a[7]);