could any one help me. i am making an app, and in the java, numbers are send to a int array and i need to check if any of the numbers in the array repeated and if there are to c
I'd write something like:
public boolean hasRepeatedNumbers(int[] a) { int[] b = new int[a.length]; System.arraycopy(a, 0, b, 0, a.length); Array.sort(b); int i; for (i = 1; i < b.length; i++) { if (b[i] == b[i-1]) return true; } return false; }
This works because we sort the array (actually a copy of the array, since we don't want to mess with the caller's original array), then detect adjacent duplicates. Since the array is sorted, all duplicates will necessarily be adjacent.
If the array is large and copying it is expensive, you can do it in place (but document the function to this effect).
If you can't sort the array, you can also build a set, then iterate through the array testing if the current value is in the set -- if it is, it's a duplicate. If not, place it into the set.