-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathfind_duplicate_number.cpp
42 lines (34 loc) · 1.06 KB
/
find_duplicate_number.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Non - optimal solution:
// class Solution {
// public:
// int findDuplicate(vector<int>& nums) {
// sort(nums.begin(), nums.end());
// for(auto i = nums.begin(); i != nums.end()-1; i++){
// if(*(i) == *(i+1))
// return *(i);
// }
// return -1;
// }
// };
// Optimal solution - O(n) || O(1)
class Solution {
public:
// Very similar to find the point where there is a loop in the linked list
// Treat array as a circular list with the duplicate element as the intersection point
// Hair and Tortoise method
int findDuplicate(vector<int>& nums) {
if(nums.size() <= 1) return -1;
int fast = 0, slow = 0;
while(true) {
slow = nums[slow];
fast = nums[nums[fast]]; // take index as array element
if(slow == fast) break;
}
fast = 0;
while(slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
};