|
1 | 1 | // Source : https://leetcode.com/problems/find-the-duplicate-number/ |
2 | | -// Author : Calinescu Valentin |
| 2 | +// Author : Hao Chen, Calinescu Valentin |
3 | 3 | // Date : 2015-10-19 |
4 | 4 |
|
5 | 5 | /*************************************************************************************** |
|
9 | 9 | * Assume that there is only one duplicate number, find the duplicate one. |
10 | 10 | * |
11 | 11 | * 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 | + * |
17 | 18 | * Credits: |
18 | 19 | * Special thanks to @jianchao.li.fighter for adding this problem and creating all test |
19 | 20 | * cases. |
20 | 21 | * |
21 | 22 | ***************************************************************************************/ |
22 | 23 |
|
23 | 24 |
|
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> |
36 | 25 | class Solution { |
37 | 26 | 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 | + // |
38 | 33 | 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; |
43 | 51 | } |
44 | 52 | }; |
0 commit comments