Check for recurring numbers in a int[] Java
I want to be able to tell if a any number in an int[] appears 3 or more times? How can I do this?
Would开发者_开发技巧 be awesome to have method
boolean hasTriples(int[] numbers) {
//some code
}
Create a Map<Integer, Integer>
, and let integer n map to the number of occurrences of n.
Loop through the array to populate the map, then loop through the keys in the map to check which keys map to a value >= 3.
Here's some code to get you started:
int[] arr = { 1, 3, 2, 3, 3, 4, 2, 2 };
Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
// Count occurrencies
for (int i : arr) {
if (!counts.containsKey(i))
counts.put(i, 0);
counts.put(i, 1 + counts.get(i));
}
// Print how many times each number occurs in arr.
for (int i : counts.keySet())
System.out.printf("i: %d, count: %d%n", i, counts.get(i));
public boolean anyRepeatThreeTimes( int [] array ) {
Map<Integer, Integer > map = new HashMap<Integer, Integer>();
for ( int index = 0; index < array.length; index++ ) {
Integer total = map.get(array[ index ]);
int count;
if ( total == null ) {
count = 1;
}
else {
count = total + 1;
if ( count >= 3 ) {
return true;
}
}
map.put( array[ index ], count );
}
return false;
}
Here's what's going on:
- You pass in the array of ints.
- You set up a map of array values to a count of the value.
You walk the array. For each integer in the array:
a. you retrieve the current count for that array value
b. if no value exists, then start with a value of 1
c. if a value does exist in the map for the given value, add one to it
d. if the value retrieved from the map + 1 exceeds your limit of 3, then you have demonstrated that there is a value in the array that is repeated at least three times.
if you make it to the end of the loop without ever returning true, then return false instead, because no value is repeated 3 times.
Here is a way to do it without using any extra classes such as the Map class. It might be slower but hopefully is easier to understand.
public boolean hasTriples(int[] list) {
for (int i = 0; i < list.length; i++){
int duplicates = 0;
for (int j = i+1; j < list.length; j++){
if (list[i] == list[j]) {
duplicates++;
if (duplicates >= 3) return true;
}
}
}
return false;
}
Here is what this code is doing. The outer for loop is running through the list to make sure that every value is checked for duplicates. The inner loops runs through the remeinder of the list to check how many duplicate values there are. If three or more duplicates are found the function will return true and not process the rest of the list. If the outer for loop finishes without the method returning true false is returned as there must not be any three duplicates.
Hope this helps!
精彩评论