-
Notifications
You must be signed in to change notification settings - Fork 0
/
Question1.cpp
41 lines (33 loc) · 880 Bytes
/
Question1.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
// Here I started My Journey with the questions :->
1 -> Find the Duplicate Number
Solution :
class Solution {
public:
int findDuplicate(vector<int>& nums) {
sort(nums.begin(),nums.end());
for(int i=0;i<nums.size();i++){
if(nums[i]==nums[i+1])return nums[i];
}
return 0;
}
};
Another Aproach using Fast And Slow Pointer
class Solution {
public:
int findDuplicate(std::vector<int>& nums) {
int slow = nums[0];
int fast = nums[0];
// Find the intersection point of the two pointers
do {
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow != fast);
// Find the entrance of the cycle
slow = nums[0];
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
};