Android (method for checking an arrays for repeated numbers?)

前端 未结 3 1844
时光取名叫无心
时光取名叫无心 2021-01-28 23:40

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

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-29 00:17

    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.

提交回复
热议问题