题目描述

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中第一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
返回描述:
如果数组中有重复的数字,函数返回true,否则返回false。
如果数组中有重复的数字,把重复的数字放到参数duplication[0]中。(ps:duplication已经初始化,可以直接赋值使用。)

代码

方法一

  1. 如果没有重复数字,那么正常排序后,数字i应该在下标为i的位置,所以思路是重头扫描数组,遇到下标为i的数字如果不是i的话,
  2. (假设为m),那么我们就拿与下标m的数字交换。在交换过程中,如果有重复的数字发生,那么终止返回ture
  1. //存在BUG
  2. public int findRepeatNumber(int[] nums) {
  3. for (int i = 0; i < nums.length; ++i) {
  4. while (nums[i] != i) {
  5. if (nums[i] == nums[nums[i]]) {
  6. return nums[i];
  7. }
  8. int temp = nums[i];
  9. nums[i] = nums[temp];
  10. nums[temp] = temp;
  11. }
  12. }
  13. return -1;
  14. }

方法二

  1. class Solution {
  2. public:
  3. // 2, 3, 1, 0, 2, 5
  4. // 1, 3, 2, 0, 2, 5
  5. // 3, 1, 2, 0, 2, 5
  6. // 0, 1, 2, 3, 2, 5
  7. int duplicate(vector<int> &numbers) {
  8. unordered_map<int, int> hash;
  9. for (int i = 0; i < numbers.size(); i++) {
  10. hash[numbers[i]]++;
  11. if (hash[numbers[i]] > 1) {
  12. return numbers[i];
  13. }
  14. }
  15. return -1;
  16. }
  17. };