剑指offer之【数组中重复的数字】

题目:

  数组中重复的数字

链接:

  https://www.nowcoder.com/practice/623a5ac0ea5b4e5f95552655361ae0a8?tpId=13&tqId=11203&rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题目描述:

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

思路:

  因为 n个数 且属于0----n-1;

  所以如果是排好序因该是该位置上的数字应该等于该位置,如不等于进行交换,交换之前要判断要交换的位置的值与当前位置的值是否相等。

代码:

  

 1 class Solution {
 2 public:
 3     bool duplicate(int numbers[], int length, int* duplication){
 4         if(numbers == nullptr || length<=0){
 5             *duplication = -1;
 6             return false;
 7         }
 8         for(int i =0;i<length;++i){
 9             if(numbers[i] != i){
10                 while(numbers[i] != i){
11                     if(numbers[i]==numbers[numbers[i]]){
12                         *duplication = numbers[i];
13                         return true;
14                     }
15                     swap(numbers[i],numbers[numbers[i]]);
16                 }
17             }
18         }
19         *duplication = -1;
20         return false;
21     }
22     bool iseq(int numbers[], int i ,int j){
23         return numbers[i] == numbers[j];
24     }
25 };

 

posted @ 2017-06-07 22:58  我是畅游海  阅读(124)  评论(0编辑  收藏  举报