码迷,mamicode.com
首页 > 编程语言 > 详细

50、剑指offer--数组中重复数字

时间:2017-06-27 13:51:49      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:16px   ace   ==   长度   开始   space   solution   log   parameter   

题目描述
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
 
解题思路:从头开始遍历数组,例如2 3 1 0 2 5 3
遍历到2 i != a[i] 交换i和a[i]位置的数字 变为 1 3 2 0 2 5 3
1 交换变为 3 1 2 0 2 5 3
3 交换变为 0 1 2 3 2 5 3
一直遍历直到 2  2 == a[a[2]] 存入2 返回true
全部遍历完返回false
 1 class Solution {
 2 public:
 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
 7     // Return value:       true if the input is valid, and there are some duplications in the array number
 8     //                     otherwise false
 9     bool duplicate(int numbers[], int length, int* duplication) {
10         if(length <= 0)
11             return false;
12         for(int i=0;i<length;i++)
13         {
14             if(numbers[i] <0 || numbers[i]>length-1)
15             {
16                 return false;
17             }
18         }
19         for(int i=0;i<length;i++)
20         {
21             while(numbers[i] != i)
22             {
23                 if(numbers[i] == numbers[numbers[i]])
24                 {
25                     *duplication = numbers[i];
26                     return true;
27                 }
28                 //交换
29                 int temp = numbers[i];
30                 numbers[i] = numbers[temp];
31                 numbers[temp] = temp;
32             }
33         }
34         return false;
35     }
36 };

 

50、剑指offer--数组中重复数字

标签:16px   ace   ==   长度   开始   space   solution   log   parameter   

原文地址:http://www.cnblogs.com/qqky/p/7084602.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!