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

题目链接:

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
示例1
 
解题思路:
 
我都是用Hash做的,也有别的方法,这个再次复习的时候可以考虑。
 1 import java.util.HashMap;
 2 public class Solution {
 3     // Parameters:
 4     //    numbers:     an array of integers
 5     //    length:      the length of array numbers
 6     //    duplication: (Output) the duplicated number in the array number,length of duplication array is 1,so using duplication[0] = ? in implementation;
 7     //                  Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++
 8     //    这里要特别注意~返回任意重复的一个,赋值duplication[0]
 9     // Return value:       true if the input is valid, and there are some duplications in the array number
10     //                     otherwise false
11     public boolean duplicate(int numbers[],int length,int [] duplication) {
12         
13         HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
14         
15         for(int i=0;i<length;i++)
16         {
17             if(map.containsKey(numbers[i]))
18             {
19                 int value = map.get(numbers[i]);
20                 map.put(numbers[i],++value);
21             }
22             else
23             {
24                 map.put(numbers[i],1);
25             }
26         }
27         
28         for(int i =0;i<length;i++)
29         {
30             if(map.get(numbers[i])==2)
31             {
32                 duplication[0] = numbers[i];
33                 return true;
34                 
35             }
36         }
37         return false;
38     
39     }
40 }
 1 import java.util.HashMap;
 2 public class Solution {
 3     // Parameters:
 4     //    numbers:     an array of integers
 5     //    length:      the length of array numbers
 6     //    duplication: (Output) the duplicated number in the array number,length of duplication array is 1,so using duplication[0] = ? in implementation;
 7     //                  Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++
 8     //    这里要特别注意~返回任意重复的一个,赋值duplication[0]
 9     // Return value:       true if the input is valid, and there are some duplications in the array number
10     //                     otherwise false
11     public boolean duplicate(int numbers[],int length,int [] duplication) {
12         
13         for(int i=0;i<length;i++)
14         {
15             while(numbers[i]!=i)
16             {
17                 if(numbers[i]==numbers[numbers[i]])
18                 {
19                     duplication[0] = numbers[i];
20                     return true;
21                 }
22                 int temp = numbers[i];
23                 numbers[i] = numbers[temp];
24                 numbers[temp] = temp;
25             }
26         }
27         return false;
28     
29     }
30 }
原文地址:https://www.cnblogs.com/wangyufeiaichiyu/p/10872621.html