数组中重复的数字

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

 1 using System.Collections;
 2 namespace JianZhiOffer
 3 {
 4     class DuplicateInArray
 5     {
 6         public bool duplicate(int[] numbers, int[] duplication)
 7         {
 8             // write code here
 9             if (numbers == null || numbers.Length < 1)
10                 return false;
11 
12             Queue q = new Queue();
13 
14             for (int i = 0; i < numbers.Length; i++)
15             {
16                 if (q.Contains(numbers[i]))
17                 {
18                     duplication[0] = numbers[i];
19                     return true;
20                 }
21                 else 
22                 {
23                     q.Enqueue(numbers[i]);
24                 }
25             }
26 
27             return false;
28         }
29     }
30 }

 

posted on 2019-11-16 23:44  雷损  阅读(127)  评论(0编辑  收藏  举报

导航