How to delete minimum and maximum from array? - java

I'm a newbie in java. I'm trying to find minimum maximum element in array and then delete the minimum and maximum. This is the code I wrote, it's only working for maximum not for minimum.
public class delminmax {
public static void main(String[] args) {
int [] nums = {10,50,20,90,22};
int max = 0;
int min = 0;
for (int i=0; i<nums.length; i++) {
if (nums[i]> max)
max = nums[i];
}
System.out.println("The max number is "+ max);
for (int i=0;i<nums.length;i++)
if (max==nums[i]) {
for (int j=i; j<nums.length-1;j++)
nums[j]= nums[j+1];
}
for (int i=0;i<nums.length-1;i++)
System.out.print(nums[i]+ " " + "\n");
for (int i=0; i<nums.length; i++) {
if (nums[i]< min)
min = nums[i];
}
System.out.println("The min number is "+ min);
for (int i=0;i<nums.length;i++)
if (min==nums[i]) {
for (int j=i; j<nums.length-1;j++)
nums[j]= nums[j+1];
}
for (int i=0;i<nums.length-1;i++)
System.out.println(nums[i] + " ");
}
}

You can't delete elements from an array, an array has a fixed length determined at creation time. You can instead create a new array with two fewer elements. You only need one loop to determine the min and max, but instead of doing so directly it's cleaner in my opinion to track the indices of the min and max elements. Then you can use a second loop to skip those elements when you copy nums to the new array. Like,
int[] nums = { 10, 50, 20, 90, 22 };
int mini = 0, maxi = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i] < nums[mini]) {
mini = i;
}
if (nums[i] > nums[maxi]) {
maxi = i;
}
}
System.out.printf("The min = %d, the max = %d%n", nums[mini], nums[maxi]);
int[] newNums = new int[nums.length - 2]; // A new array, with two fewer elements
int p = 0;
for (int i = 0; i < nums.length; i++) {
if (i != mini && i != maxi) {
newNums[p++] = nums[i];
}
}
System.out.println(Arrays.toString(newNums));
Which outputs
The min = 10, the max = 90
[50, 20, 22]

Using Java 8
You can try by using streams with the approach below:
Approach Here:
I have converted the given array of Integers in the sorted list and then find the minimum and maximum integer from that list using any of the below method and then filtered the nums Array with these min and max integers and converted the filtered list back to Array of Integers.
To find the minimum and maximum integer in an array
1) By using IntSummaryStatistics from stream
IntSummaryStatistics statistics = Arrays.stream(nums).summaryStatistics();
int minNum = statistics.getMin();
int maxNum = statistics.getMax();
2) By Sorting the array
List<Integer> mainList = Arrays.stream(nums).boxed().sorted()
.collect(Collectors.toList());
int minNum = mainList.get(0);
int maxNum = mainList.get(mainList.size()-1);
Note: It will remove all the occurrences of minimum and maximum integer from the given array.
public class Test {
public static void main(String[] args) {
int [] nums = {10,50,90,20,5,90,22,5};
IntSummaryStatistics statistics = Arrays.stream(nums).summaryStatistics();
int minNum = statistics.getMin();
int maxNum = statistics.getMax();
int[] num = Arrays.stream(nums)
.filter(x -> x != minNum && x != maxNum).toArray();
for(int i:num){
System.out.print(i + " ");
}
}
}
Testcases:
Input: {10,50,90,20,5,90,22,5}
Output: 10 50 20 22
Input: {10, 50, 20, 90, 22}
Output: 50 20 22

Arrays are something whose length/size can't be changed. They are created with a fixed size which can't be modified. If you want to use the functionality you mentioned, it's better to go for a list, preferably ArrayList
List<Integer> list= new ArrayList<Integer>();
You can always return an ArrayList as an array if need be. You can search for functions like
list.toArray()

Related

Sorting an array by number of digits in each element from largest to smallest using loops java

I'm trying to sort an array by the number of digits in each element from largest to smallest. This technically works but it seems to sort the array by value as well. For example, instead of printing out 1234 700 234 80 52, it should print 1234 234 700 52 80 as 234 is before 700 in the original array.
public class Sort {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {52, 234, 80, 700, 1234};
int temp = 0;
//Displaying elements of original array
System.out.println("Elements of original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
//Sort the array in descending order
//Math function is used to find length of each element
for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
if(Math.log10(arr[i]) + 1 < Math.log10(arr[j]) + 1) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println();
//Displaying elements of array after sorting
System.out.println("Elements of array sorted in descending order: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
The easiest way to find the length of the number is to convert it into a String and then call the method length on it.
int number = 123;
String numberAsString = String.valueOf(number);
int length = numberAsString.length(); // returns 3
But you also could do it by division. The following method takes a number and divides by multiples of 10.
divide by 1 (we have at least a length of 1)
division by 10 > 0 (we have at least a length of 2)
division by 100 > 0 (we have at least a length of 3)
...
the variable i is used as dividend and the variable j is used as counter. j counts the length of the number.
As soon as number / i equals zero we return the counter value.
public int lengthOfNumber(int number) {
if (number == 0) {
return 1;
}
for (int i = 1, j = 0; ; i *= 10, j++) {
if (number / i == 0) {
return j;
}
}
}
There are multiple ways to sort the array. Here are some examples (I used the string version for comparing the values).
Use nested for-loop
public void sortArray(int[] array) {
for (int i = 0; i < array.length; i++) {
int swapIndex = -1;
int maxLength = String.valueOf(array[i]).length();
for(int j = i + 1; j < array.length; j++) {
int length2 = String.valueOf(array[j]).length();
if (maxLength < length2) {
maxLength = length2;
swapIndex = j;
}
}
if (swapIndex > -1) {
int temp = array[i];
array[i] = array[swapIndex];
array[swapIndex] = temp;
}
}
}
I used a variable swapIndex which is initialized with -1. This way we can avoid unnecessary array operations.
We take the first element in the outer for-loop and go through the rest of the array in the inner for-loop. we only save a new swapIndex if there is a number in the rest of the array with a higher length. if there is no number with a higher length, swapIndex remains -1. We do a possible swap only in the outer for-loop if necessary (if swapIndex was set).
Using Arrays.sort()
If you want to use Arrays.sort you need to convert your array from primitive type int to Integer.
public void sortArray(Integer[] array) {
Arrays.sort(array, (o1, o2) -> {
Integer length1 = String.valueOf(o1).length();
Integer length2 = String.valueOf(o2).length();
return length2.compareTo(length1);
});
}
Using a recursive method
public void sortArray(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
String current = String.valueOf(array[i]);
String next = String.valueOf(array[i + 1]);
if (current.length() < next.length()) {
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
// here you do a recursive call
sortArray(array);
}
}
}

How do I find the maximum number in an array in Java

I am given the array measurements[]. I am supposed to write a for loop that goes through all the numbers and each time a number maximum is reached, the variable maximum is replaced. In the code I have so far, the output is saying that it cannot find the symbol i, but I thought that was the symbol I am supposed to use within a for-loop. Here is my code:
double maximum = measurements[0];
for (i = 0; i < measurements.length; i++) {
if (array[i] > largest) {
largest = array[i];
}
}
System.out.println(maximum);
You can also do this using Java stream api :
double maximum = Arrays.stream(measurements).max();
System.out.println(maximum);
Or a more concise code:
double maximum = Double.MIN_VALUE;
for(double measurement : measurements) {
maximum = Math.max(maximum, measurement);
}
System.out.println(maximum);
Or, sort the array and return the last one
Arrays.sort(measurements);
System.out.println(measurements[measurements.length-1]);
you can try this -
class MaxNumber
{
public static void main(String args[])
{
int[] a = new int[] { 10, 3, 50, 14, 7, 90};
int max = a[0];
for(int i = 1; i < a.length;i++)
{
if(a[i] > max)
{
max = a[i];
}
}
System.out.println("Given Array is:");
for(int i = 0; i < a.length;i++)
{
System.out.println(a[i]);
}
System.out.println("Max Number is:" + max);
}
}
You have not declared i inside the for loop or before the for loop.
double maximum = measurements[0];
for (int i = 0; i < measurements.length; i++) { //You can declare i here.
if (array[i] > largest) {
largest = array[i];
}
}
System.out.println(maximum);
You can also declare i before the for loop also

Count how many integers were displayed in an array

I got an 100 random elements array, each element is in range of 0-10, and i need to count each integer how many times it was typed (e.g. 1,2,2,3,8,8,4...)
OUTPUT:
1 - 1
2 - 2
3 - 1
8 - 2
4 - 1
My code so far is:
import java.util.Random;
public class Asses1 {
public static void main(String[] args) {
getNumbers();
}
private static int randInt() {
int max = 10;
int min = 0;
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static int[] getNumbers() {
int number = 100;
int[] array = new int[number];
for (int i = 0; i < array.length; i++) {
System.out.println(randInt());
}
System.out.println(number+" random numbers were displayed");
return array;
}
}
Add this method, which will do the counting:
public static void count(int[] x) {
int[] c=new int[11];
for(int i=0; i<x.length; i++)
c[x[i]]++;
for(int i=0; i<c.length; i++)
System.out.println(i+" - "+c[i]);
}
and change the main into this so that you call the previous method:
public static void main(String[] args) {
count(getNumbers());
}
Also, change the for loop in getNumbers into this in order to fill array with the generated numbers, not just printing them:
for (int i = 0; i < array.length; i++) {
array[i] = randInt();
System.out.println(array[i]);
}
Here is how it can be done in java 8
// Retrieve the random generated numbers
int[] numbers = getNumbers();
// Create an array of counters of size 11 as your values go from 0 to 10
// which means 11 different possible values.
int[] counters = new int[11];
// Iterate over the generated numbers and for each number increment
// the counter that matches with the number
Arrays.stream(numbers).forEach(value -> counters[value]++);
// Print the content of my array of counters
System.out.println(Arrays.toString(counters));
Output:
[12, 11, 7, 6, 9, 12, 8, 8, 10, 9, 8]
NB: Your method getNumbers is not correct you should fix it as next:
public static int[] getNumbers() {
int number = 100;
int[] array = new int[number];
for (int i = 0; i < array.length; i++) {
array[i] = randInt();
}
System.out.println(number+" random numbers were displayed");
return array;
}
int[] array2 = new int[11];
for (int i = 0; i < array.length; i++){
array2[randInt()]++
}
for (int i = 0; i < array.length; i++)
System.out.println(String.valueOf(i) + " - " + String.valueOf(array2[i]));
What I have done is:
Create an helping array array2 for storing number of occurences of each number.
When generating numbers increment number of occurences in helping array.
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
int temp;
for (int i = 0; i < array.length; i++) {
temp=randInt();
if(map.containsKey(temp)){
map.put(temp, map.get(temp)+1);
}else{
map.put(temp, 1);
}
}

Get indices of n maximums in java array

I have an array of size 1000. How can I find the indices (indexes) of the five maximum elements?
An example with setup code and my attempt are displayed below:
Random rand = new Random();
int[] myArray = new int[1000];
int[] maxIndices = new int[5];
int[] maxValues = new int[5];
for (int i = 0; i < myArray.length; i++) {
myArray[i] = rand.nextInt();
}
for (int i = 0; i < 5; i++) {
maxIndices[i] = i;
maxValues[i] = myArray[i];
}
for (int i = 0; i < maxIndices.length; i++) {
for (int j = 0; j < myArray.length; j++) {
if (myArray[j] > maxValues[i]) {
maxIndices[i] = j;
maxValues[i] = myArray[j];
}
}
}
for (int i = 0; i < maxIndices.length; i++) {
System.out.println("Index: " + maxIndices[i]);
}
I know the problem is that it is constantly assigning the highest maximum value to all the maximum elements. I am unsure how to remedy this because I have to preserve the values and the indices of myArray.
I don't think sorting is an option because I need to preserve the indices. In fact, it is the indices that I need specifically.
Sorry to answer this old question but I am missing an implementation which has all following properties:
Easy to read
Performant
Handling of multiple same values
Therefore I implemented it:
private int[] getBestKIndices(float[] array, int num) {
//create sort able array with index and value pair
IndexValuePair[] pairs = new IndexValuePair[array.length];
for (int i = 0; i < array.length; i++) {
pairs[i] = new IndexValuePair(i, array[i]);
}
//sort
Arrays.sort(pairs, new Comparator<IndexValuePair>() {
public int compare(IndexValuePair o1, IndexValuePair o2) {
return Float.compare(o2.value, o1.value);
}
});
//extract the indices
int[] result = new int[num];
for (int i = 0; i < num; i++) {
result[i] = pairs[i].index;
}
return result;
}
private class IndexValuePair {
private int index;
private float value;
public IndexValuePair(int index, float value) {
this.index = index;
this.value = value;
}
}
Sorting is an option, at the expense of extra memory. Consider the following algorithm.
1. Allocate additional array and copy into - O(n)
2. Sort additional array - O(n lg n)
3. Lop off the top k elements (in this case 5) - O(n), since k could be up to n
4. Iterate over the original array - O(n)
4.a search the top k elements for to see if they contain the current element - O(lg n)
So it step 4 is (n * lg n), just like the sort. The entire algorithm is n lg n, and is very simple to code.
Here's a quick and dirty example. There may be bugs in it, and obviously null checking and the like come into play.
import java.util.Arrays;
class ArrayTest {
public static void main(String[] args) {
int[] arr = {1, 3, 5, 7, 9, 2, 4, 6, 8, 10};
int[] indexes = indexesOfTopElements(arr,3);
for(int i = 0; i < indexes.length; i++) {
int index = indexes[i];
System.out.println(index + " " + arr[index]);
}
}
static int[] indexesOfTopElements(int[] orig, int nummax) {
int[] copy = Arrays.copyOf(orig,orig.length);
Arrays.sort(copy);
int[] honey = Arrays.copyOfRange(copy,copy.length - nummax, copy.length);
int[] result = new int[nummax];
int resultPos = 0;
for(int i = 0; i < orig.length; i++) {
int onTrial = orig[i];
int index = Arrays.binarySearch(honey,onTrial);
if(index < 0) continue;
result[resultPos++] = i;
}
return result;
}
}
There are other things you can do to reduce the overhead of this operation. For example instead of sorting, you could opt to use a queue that just tracks the largest 5. Being ints they values would probably have to be boxed to be added to a collection (unless you rolled your own) which adds to overhead significantly.
a bit late in answering, you could also use this function that I wrote:
/**
* Return the indexes correspond to the top-k largest in an array.
*/
public static int[] maxKIndex(double[] array, int top_k) {
double[] max = new double[top_k];
int[] maxIndex = new int[top_k];
Arrays.fill(max, Double.NEGATIVE_INFINITY);
Arrays.fill(maxIndex, -1);
top: for(int i = 0; i < array.length; i++) {
for(int j = 0; j < top_k; j++) {
if(array[i] > max[j]) {
for(int x = top_k - 1; x > j; x--) {
maxIndex[x] = maxIndex[x-1]; max[x] = max[x-1];
}
maxIndex[j] = i; max[j] = array[i];
continue top;
}
}
}
return maxIndex;
}
My quick and a bit "think outside the box" idea would be to use the EvictingQueue that holds an maximum of 5 elements. You'd had to pre-fill it with the first five elements from your array (do it in a ascending order, so the first element you add is the lowest from the five).
Than you have to iterate through the array and add a new element to the queue whenever the current value is greater than the lowest value in the queue. To remember the indexes, create a wrapper object (a value/index pair).
After iterating through the whole array, you have your five maximum value/index pairs in the queue (in descending order).
It's a O(n) solution.
Arrays.sort(myArray), then take the final 5 elements.
Sort a copy if you want to preserve the original order.
If you want the indices, there isn't a quick-and-dirty solution as there would be in python or some other languages. You sort and scan, but that's ugly.
Or you could go objecty - this is java, after all.
Make an ArrayMaxFilter object. It'll have a private class ArrayElement, which consists of an index and a value and has a natural ordering by value. It'll have a method which takes a pair of ints, index and value, creates an ArrayElement of them, and drops them into a priority queue of length 5. (or however many you want to find). Submit each index/value pair from the array, then report out the values remaining in the queue.
(yes, a priority queue traditionally keeps the lowest values, but you can flip this in your implementation)
Here is my solution. Create a class that pairs an indice with a value:
public class IndiceValuePair{
private int indice;
private int value;
public IndiceValuePair(int ind, int val){
indice = ind;
value = val;
}
public int getIndice(){
return indice;
}
public int getValue(){
return value;
}
}
and then use this class in your main method:
public static void main(String[] args){
Random rand = new Random();
int[] myArray = new int[10];
IndiceValuePair[] pairs = new IndiceValuePair[5];
System.out.println("Here are the indices and their values:");
for(int i = 0; i < myArray.length; i++) {
myArray[i] = rand.nextInt(100);
System.out.println(i+ ": " + myArray[i]);
for(int j = 0; j < pairs.length; j++){
//for the first five entries
if(pairs[j] == null){
pairs[j] = new IndiceValuePair(i, myArray[i]);
break;
}
else if(pairs[j].getValue() < myArray[i]){
//inserts the new pair into its correct spot
for(int k = 4; k > j; k--){
pairs[k] = pairs [k-1];
}
pairs[j] = new IndiceValuePair(i, myArray[i]);
break;
}
}
}
System.out.println("\n5 Max indices and their values");
for(int i = 0; i < pairs.length; i++){
System.out.println(pairs[i].getIndice() + ": " + pairs[i].getValue());
}
}
and example output from a run:
Here are the indices and their values:
0: 13
1: 71
2: 45
3: 38
4: 43
5: 9
6: 4
7: 5
8: 59
9: 60
5 Max indices and their values
1: 71
9: 60
8: 59
2: 45
4: 43
The example I provided only generates ten ints with a value between 0 and 99 just so that I could see that it worked. You can easily change this to fit 1000 values of any size. Also, rather than run 3 separate for loops, I checked to see if the newest value I add is a max value right after I add to to myArray. Give it a run and see if it works for you

Find the element with highest occurrences in an array [java]

I have to find the element with highest occurrences in a double array.
I did it like this:
int max = 0;
for (int i = 0; i < array.length; i++) {
int count = 0;
for (int j = 0; j < array.length; j++) {
if (array[i]==array[j])
count++;
}
if (count >= max)
max = count;
}
The program works, but it is too slow! I have to find a better solution, can anyone help me?
Update:
As Maxim pointed out, using HashMap would be a more appropriate choice than Hashtable here.
The assumption here is that you are not concerned with concurrency. If synchronized access is needed, use ConcurrentHashMap instead.
You can use a HashMap to count the occurrences of each unique element in your double array, and that would:
Run in linear O(n) time, and
Require O(n) space
Psuedo code would be something like this:
Iterate through all of the elements of your array once: O(n)
For each element visited, check to see if its key already exists in the HashMap: O(1), amortized
If it does not (first time seeing this element), then add it to your HashMap as [key: this element, value: 1]. O(1)
If it does exist, then increment the value corresponding to the key by 1. O(1), amortized
Having finished building your HashMap, iterate through the map and find the key with the highest associated value - and that's the element with the highest occurrence. O(n)
A partial code solution to give you an idea how to use HashMap:
import java.util.HashMap;
...
HashMap hm = new HashMap();
for (int i = 0; i < array.length; i++) {
Double key = new Double(array[i]);
if ( hm.containsKey(key) ) {
value = hm.get(key);
hm.put(key, value + 1);
} else {
hm.put(key, 1);
}
}
I'll leave as an exercise for how to iterate through the HashMap afterwards to find the key with the highest value; but if you get stuck, just add another comment and I'll get you more hints =)
Use Collections.frequency option:
List<String> list = Arrays.asList("1", "1","1","1","1","1","5","5","12","12","12","12","12","12","12","12","12","12","8");
int max = 0;
int curr = 0;
String currKey = null;
Set<String> unique = new HashSet<String>(list);
for (String key : unique) {
curr = Collections.frequency(list, key);
if(max < curr){
max = curr;
currKey = key;
}
}
System.out.println("The number " + currKey + " happens " + max + " times");
Output:
The number 12 happens 10 times
The solution with Java 8
int result = Arrays.stream(array)
.boxed()
.collect(Collectors.groupingBy(i->i,Collectors.counting()))
.values()
.stream()
.max(Comparator.comparingLong(i->i))
.orElseThrow(RuntimeException::new));
I will suggest another method. I don't know if this would work faster or not.
Quick sort the array. Use the built in Arrays.sort() method.
Now compare the adjacent elements.
Consider this example:
1 1 1 1 4 4 4 4 4 4 4 4 4 4 4 4 9 9 9 10 10 10 29 29 29 29 29 29
When the adjacent elements are not equal, you can stop counting that element.
Solution 1: Using HashMap
class test1 {
public static void main(String[] args) {
int[] a = {1,1,2,1,5,6,6,6,8,5,9,7,1};
// max occurences of an array
Map<Integer,Integer> map = new HashMap<>();
int max = 0 ; int chh = 0 ;
for(int i = 0 ; i < a.length;i++) {
int ch = a[i];
map.put(ch, map.getOrDefault(ch, 0) +1);
}//for
Set<Entry<Integer,Integer>> entrySet =map.entrySet();
for(Entry<Integer,Integer> entry : entrySet) {
if(entry.getValue() > max) {max = entry.getValue();chh = entry.getKey();}
}//for
System.out.println("max element => " + chh);
System.out.println("frequency => " + max);
}//amin
}
/*output =>
max element => 1
frequency => 4
*/
Solution 2 : Using count array
public class test2 {
public static void main(String[] args) {
int[] a = {1,1,2,1,5,6,6,6,6,6,8,5,9,7,1};
int max = 0 ; int chh = 0;
int count[] = new int[a.length];
for(int i = 0 ; i <a.length ; i++) {
int ch = a[i];
count[ch] +=1 ;
}//for
for(int i = 0 ; i <a.length ;i++) {
int ch = a[i];
if(count[ch] > max) {max = count[ch] ; chh = ch ;}
}//for
System.out.println(chh);
}//main
}
Here's a java solution --
List<Integer> list = Arrays.asList(1, 2, 2, 3, 2, 1, 3);
Set<Integer> set = new HashSet(list);
int max = 0;
int maxtemp;
int currentNum = 0;
for (Integer k : set) {
maxtemp = Math.max(Collections.frequency(list, k), max);
currentNum = maxtemp != max ? k : currentNum;
max = maxtemp;
}
System.out.println("Number :: " + currentNum + " Occurs :: " + max + " times");
int[] array = new int[] { 1, 2, 4, 1, 3, 4, 2, 2, 1, 5, 2, 3, 5 };
Long max = Arrays.stream(array).boxed().collect(Collectors.groupingBy(i -> i, Collectors.counting())).values()
.stream().max(Comparator.comparing(Function.identity())).orElse(0L);
public static void main(String[] args) {
int n;
int[] arr;
Scanner in = new Scanner(System.in);
System.out.println("Enter Length of Array");
n = in.nextInt();
arr = new int[n];
System.out.println("Enter Elements in array");
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
int greatest = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] > greatest) {
greatest = arr[i];
}
}
System.out.println("Greatest Number " + greatest);
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (greatest == arr[i]) {
count++;
}
}
System.out.println("Number of Occurance of " + greatest + ":" + count + " times");
in.close();
}
In continuation to the pseudo-code what you've written try the below written code:-
public static void fetchFrequency(int[] arry) {
Map<Integer, Integer> newMap = new TreeMap<Integer, Integer>(Collections.reverseOrder());
int num = 0;
int count = 0;
for (int i = 0; i < arry.length; i++) {
if (newMap.containsKey(arry[i])) {
count = newMap.get(arry[i]);
newMap.put(arry[i], ++count);
} else {
newMap.put(arry[i], 1);
}
}
Set<Entry<Integer, Integer>> set = newMap.entrySet();
List<Entry<Integer, Integer>> list = new ArrayList<Entry<Integer, Integer>>(set);
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
#Override
public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
return (o2.getValue()).compareTo(o1.getValue());
}
});
for (Map.Entry<Integer, Integer> entry : list) {
System.out.println(entry.getKey() + " ==== " + entry.getValue());
break;
}
//return num;
}
This is how i have implemented in java..
import java.io.*;
class Prog8
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Input Array Size:");
int size=Integer.parseInt(br.readLine());
int[] arr= new int[size];
System.out.println("Input Elements in Array:");
for(int i=0;i<size;i++)
arr[i]=Integer.parseInt(br.readLine());
int max = 0,pos=0,count = 0;
for (int i = 0; i < arr.length; i++)
{
count=0;
for (int j = 0; j < arr.length; j++)
{
if (arr[i]==arr[j])
count++;
}
if (count >=max)
{
max = count;
pos=i;
}
}
if(max==1)
System.out.println("No Duplicate Element.");
else
System.out.println("Element:"+arr[pos]+" Occourance:"+max);
}
}
Find the element with the highest occurrences in an array using java 8 is given below:
final Long maxOccurrencesElement = arr.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.max((o1, o2) -> o1.getValue().compareTo(o2.getValue()))
.get()
.getKey();
You can solve this problem in one loop with without using HashMap or any other data structure in O(1) space complexity.
Initialize two variables count = 0 and max = 0 (or Integer.MIN_VALUE if you have negative numbers in your array)
The idea is you will scan through the array and check the current number,
if it is less than your current max...then do nothing
if it is equal to your max ...then increment the count variable
if it is greater than your max..then update max to current number and set count to 1
Code:
int max = 0, count = 0;
for (int i = 0; i < array.length; i++) {
int num = array[i];
if (num == max) {
count++;
} else if (num > max) {
max = num;
count = 1;
}
}
Here is Ruby SOlution:
def maxOccurence(arr)
m_hash = arr.group_by(&:itself).transform_values(&:count)
elem = 0, elem_count = 0
m_hash.each do |k, v|
if v > elem_count
elem = k
elem_count = v
end
end
"#{elem} occured #{elem_count} times"
end
p maxOccurence(["1", "1","1","1","1","1","5","5","12","12","12","12","12","12","12","12","12","12","8"])
output:
"12 occured 10 times"

Categories

Resources