Skip to content

Commit 8c3448a

Browse files
committed
correct the algorithm to meet the problem's requirement - the array is ready only
1 parent 5b43c59 commit 8c3448a

File tree

1 file changed

+30
-22
lines changed

1 file changed

+30
-22
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Source : https://leetcode.com/problems/find-the-duplicate-number/
2-
// Author : Calinescu Valentin
2+
// Author : Hao Chen, Calinescu Valentin
33
// Date : 2015-10-19
44

55
/***************************************************************************************
@@ -9,36 +9,44 @@
99
* Assume that there is only one duplicate number, find the duplicate one.
1010
*
1111
* Note:
12-
* You must not modify the array (assume the array is read only).
13-
* You must use only constant, O(1) extra space.
14-
* Your runtime complexity should be less than O(n2).
15-
* There is only one duplicate number in the array, but it could be repeated more than
16-
* once.
12+
* > You must not modify the array (assume the array is read only).
13+
* > You must use only constant, O(1) extra space.
14+
* > Your runtime complexity should be less than O(n2).
15+
* > There is only one duplicate number in the array, but it could be repeated more than
16+
* once.
17+
*
1718
* Credits:
1819
* Special thanks to @jianchao.li.fighter for adding this problem and creating all test
1920
* cases.
2021
*
2122
***************************************************************************************/
2223

2324

24-
25-
/*
26-
* Solutions
27-
* =========
28-
*
29-
* A simple solution would be to sort the array and then look for equal consecutive elements.
30-
*
31-
* Time Complexity: O(N log N)
32-
* Space Complexity: O(1)
33-
*
34-
*/
35-
#include <algorithm>
3625
class Solution {
3726
public:
27+
//
28+
// This problem can be transfromed to "Linked List Cycle" problem.
29+
// There are two pointers, one goes one step, another goes two steps.
30+
//
31+
// Refer to: https://en.wikipedia.org/wiki/Cycle_detection
32+
//
3833
int findDuplicate(vector<int>& nums) {
39-
sort(nums.begin(), nums.end());
40-
for(vector<int>::iterator it = nums.begin(); it != nums.end(); ++it)
41-
if(*it == *(it + 1))
42-
return *it;
34+
int n = nums.size();
35+
int one = n;
36+
int two = n;
37+
38+
do{
39+
one = nums[one-1];
40+
two = nums[nums[two-1]-1];
41+
} while(one != two);
42+
43+
//find the start point of the cycle
44+
one = n;
45+
while(one != two){
46+
one = nums[one-1];
47+
two = nums[two-1];
48+
}
49+
50+
return one;
4351
}
4452
};

0 commit comments

Comments
 (0)