【3. 数组中重复的数字】剑指offer-JAVA实现

190 阅读1分钟

题目描述

在一个长度为 n 的数组里的所有数字都在 0 到 n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字是重复的,也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 要求时间复杂度 O(N),空间复杂度 O(1) 例子:

 Input:
 {2, 3, 1, 0, 2, 5}
 Output:
 2 

第二种解题思路 :排序 Arrays.sort 是快排 时间复杂度nlogn

第三种解题思路 :创建一个哈希表 用空间n的代价换到时间复杂度n

第四种(正解) 解题思路:使a[i]=i 如果a[i]=a[a[i]] 即有重复 用数组duplication把他取出来。

代码:

public class Three {

public boolean duplicate(int a[],int length,int []duplication) {
    if(a==null||length<=0) return false;
    for(int i=0;i<length;i++)
        while(a[i]!=i) {
            if(a[i]==a[a[i]]) {
                duplication[0] = a[i];
                return true;
            }
            swap(a,i,a[i]);
        }
    return false;
}        

public  void swap(int []a,int i,int j) {
    int temp=a[i];
    a[i]=a[j];
    a[j]=temp;
}