Java – print out the elements in the array that occur the least
•
Java
I get an array of size 10. I want to write a program to print out the elements with the least number of occurrences and their number of occurrences
For example, for arrays: 1 2 3 3 2 2 4 4 5 4 the program should print Element: 1 5, occurrence times should be 1
So far, I have printed the most events, only one element
public class Question3 {
public static void main (String[] args) {
int[] testarray = {1,2,3,4,5,4};
int count = 0;
int bigCount = 10;
for (int i=0; i < array.length; i++) {
for (int j=0; j < array.length; j++) {
if(array[j] == array[i]) {
count++;
}
}
if(count > bigCount) {
bigCount = count;
array[i] = random;
}
}
System.out.println("num of elements and occurences: " + maxCount);
}
}
Solution
You need a data structure to store each unique element, and its number. Map < integer, integer > may be your best choice Iterate over your array as you do now and keep counting Something like this:
public static void main(String[] args) {
int[] array = {1,4};
//create the map like this: <Element,Count>
Map<Integer,Integer> counts = new HashMap<>();
for (Integer i : array) {
if (counts.get(i) == null) {
counts.put(i,1);
} else {
counts.put(i,counts.get(i) + 1);
}
}
//find min value by sorting values and taking top element
List<Integer> cs = new ArrayList<Integer>(counts.values());
Collections.sort(cs);
int minVal = cs.get(0);
//find elements with minVal as their count
List<Integer> minelements = new ArrayList<>();
for (Entry<Integer,Integer> entry : counts.entrySet()) {
if (entry.getValue() == minVal) {
minelements.add(entry.getKey());
}
}
//spit out each element and the count
for (Integer i : minelements) {
System.out.println("Element: " + i + " Number of occurences: "
+ minVal);
}
}
It's not very efficient, but it's done
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
