Home > Blockchain >  Find n number of occurrences of numbers Int inside a non sorted java array
Find n number of occurrences of numbers Int inside a non sorted java array

Time:10-16

I created a class that finds the number of n occurrences for numbers in an Int non sorted Java array. I need to improve it so i do not have to use for loop inside another for. The array can take maximum 99 items. The array can not be sorted. So no sorting allowed by the use cases. Also no imports allowed. You can run the code here. Any help appreciated.

    import java.util.Arrays;
    
    public class Solution {
        
         public static void main(String args[])  
        {  
            Solution newInstance = new Solution();
           int[] myIntArray = {1,2,6,2,3,3,3,4,5,5};
            newInstance.solution( myIntArray ,1);
        }
        
        public static int[] solution(int[] data, int n) {
                    
    
            int newData[] = new int[data.length];
                int indexOfNewData = 0;
                int timesCurrentTempItemFound = 0;
    
                 System.out.println ("temp array: "   Arrays.toString(data)   "\n");
    
                for (int k=0; k<data.length; k  ) {
    
                    int currentTempItem = data[k];
                    timesCurrentTempItemFound = 0;
    
                    for (int i=0; i<data.length; i  ) {
                        if (currentTempItem == data[i]) {
                            timesCurrentTempItemFound  ;
                        }
                    }
    
                    if (timesCurrentTempItemFound == n) {
    
                        boolean itemAlreadyExists = false;
    
                        for (int index=0; index<data.length; index  ) {
                            if (data[k] == newData[index]) {
                                itemAlreadyExists = true;
                            }
                        }
    
                        if (itemAlreadyExists == false) {
                            newData[indexOfNewData] = data[k];
                            indexOfNewData  ;
                        }
                    }
                }
                
                indexOfNewData = 0;
                for(int i = 0; i<newData.length; i  ) {
                    if(newData[i] != 0) {
                        newData[indexOfNewData] = newData[i];
                        indexOfNewData  ;
                    }
    
                }
                int totalItemsInDataArrayWithoutZeros = indexOfNewData;
    
                int newDataArray[] = new int[totalItemsInDataArrayWithoutZeros];
    
                for (int i=0; i<totalItemsInDataArrayWithoutZeros; i  ) {
                    newDataArray[i] = newData[i];
                }
     System.out.println ("temp array remove zeros: "   Arrays.toString(newDataArray)   "\n");
                return newDataArray;
    }

}

CodePudding user response:

You can use a hashmap to store the numbers as keys and frequencies as values. Take a look at the 2nd method of this article that covers this in detail

CodePudding user response:

The original requirement for problem has been provided by OP in this comment.

It turns out that imports are allowed contrary to what was specified in the question.

So instead of performing redundant brute-force iterations in the nested loop, you can generate a Map of occurrences of each element in the given array.

The next step is to find the number of values of the Map that are less than n, that would be the size of the resulting array.

Then, to preserve the order, iterate over the given array and filter out elements that have the number of occurrences greater than n. The elements having the number of occurrences less or equal to n can be stored into the array.

That's how the implementation might look like:

public int[] solution(int[] data, int n) {
    Map<Integer, Integer> frequencies = new HashMap<>();
    for (int next: data) {
        frequencies.merge(next, 1, Integer::sum);
    }

    int[] result = new int[getArraySize(frequencies, n)];
    int index = 0;
    for (int next: data) {
        if (frequencies.get(next) <= n) {
            result[index  ] = next;
        }
    }
    return result;
}

public int getArraySize(Map<Integer, Integer> frequencies, int n) {
    int size = 0;
    for (int freq: frequencies.values()) {
        if (freq <= n) size  ;
    }
    return size;
}

The same logic can be implemented using Stream API:

public static int[] solution(int[] data, int n) {
    Map<Integer, Integer> frequencies = getFrequencies(data);

    return Arrays.stream(data)
        .filter(i -> frequencies.get(i) <= n)
        .toArray();
}

public static Map<Integer, Integer> getFrequencies(int[] data) {
    
    return Arrays.stream(data)
        .boxed()
        .collect(Collectors.toMap(
            Function.identity(),
            i -> 1,
            Integer::sum
        ));
}
  •  Tags:  
  • java
  • Related