剑指offer 50.数组中重复的数字

剑指offer 50.数组中重复的数字

题目

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。

思路

没什么特殊的,先判断特殊情况,然后遍历就行,如果数组已经有了,直接返回。

代码

    public boolean duplicate(int numbers[], int length, int[] duplication) {
    if (numbers == null || length <= 0) {
      return false;
    }

    for (int i : numbers) {
      if (i < 0 || i > length - 1) {
        return false;
      }
    }
    int[] ans = new int[length];
    for (int i : numbers) {
      if (ans[i] == 0) {
        ans[i] = i;
      } else {
        duplication[0] = i;
        return true;
      }
    }
    return false;
  }
原文地址:https://www.cnblogs.com/blogxjc/p/12421596.html