剑指offer-数组中重复的数字

题目描述

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
 
方法一:使用数组记录数字是否出现过,时间复杂度为O(n),空间复杂度为O(n)
 1 public boolean duplicate(int numbers[],int length,int [] duplication) {//数组 my
 2         if(null==numbers||length!=numbers.length){
 3             return false;
 4         }
 5         boolean[] num = new boolean[length];
 6         for(int i=0;i<length;i++){
 7             if(num[numbers[i]]){
 8                 duplication[0]=numbers[i];
 9                 return true;
10             }
11             else{
12                 num[numbers[i]]=true;
13             }
14         }
15         return false;
16     }

方法二:修改原始数组(不推荐),访问过的数,数组中对应位置值-length,时间复杂度为O(n),空间复杂度为O(1)

 1  public boolean duplicate(int numbers[],int length,int [] duplication) {//数组 mytip
 2         if(null==numbers||length!=numbers.length){
 3             return false;
 4         }
 5         for(int i=0;i<length;i++){
 6             int num = numbers[i];
 7             if(num<0){
 8                 num += length;
 9             }
10             if(numbers[num]<0){
11                 duplication[0]=num;
12                 return true;
13             }
14             else{
15                 numbers[num] -= length;
16             }
17         }
18         return false;
19     }

方法三:使用HashSet,此方法通用,,时间复杂度为O(n),空间复杂度为O(n)

 1 public boolean duplicate(int numbers[],int length,int [] duplication) {//set my
 2         if(null==numbers||length!=numbers.length){
 3             return false;
 4         }
 5         Set<Integer> set = new HashSet<>();
 6         for(int i=0;i<length;i++){
 7             if(set.contains(numbers[i])){
 8                 duplication[0]=numbers[i];
 9                 return true;
10             }
11             else{
12                 set.add(numbers[i]);
13             }
14         }
15         return false;
16     }
原文地址:https://www.cnblogs.com/zhacai/p/10672835.html