《剑指offer》数组中重复的数字

题目描述

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

解题思路

让数组中的每个数都放置在数字对应下标的位置,比方说数字0应该在下标为0的地方,数字4应该在下标为4的地方。从下标为0的地方开始遍历一直交换位置直到交换完,如果我们检查到需要交换的位置上已经有了和它匹配的数字,那么显然这个数字是个重复的,返回就行了。

代码是在牛客网上提交的,一开始写了三行交换,结果编译时间太长直接GG,于是写了个函数hhh,好难做人。

参考代码

public class Solution {
    public boolean duplicate(int numbers[],int length,int [] duplication) {
      if(numbers==null||length==0)
          return false;
      for(int i=0;i<length;i++){
          while(i!=numbers[i]&&numbers[numbers[i]]!=numbers[i]){
              swap(numbers,i,numbers[i]);
              //int tmp = numbers[i];
              //numbers[i] = numbers[numbers[i]];
              //numbers[numbers[i]] = tmp;
          }
          if(numbers[i]!=i&&numbers[numbers[i]]==numbers[i]){
              duplication[0]=numbers[i];
              return true;
          }
      }
      return false;
}
    private void swap(int[] nums, int i, int j) {
      int t = nums[i];	
      nums[i] = nums[j];
      nums[j] = t;
	}
}
发布了58 篇原创文章 · 获赞 5 · 访问量 6277

猜你喜欢

转载自blog.csdn.net/weixin_40992982/article/details/103961932