-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlec_10.cpp
60 lines (47 loc) Β· 1.2 KB
/
lec_10.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int n = nums.size();
sort(nums.begin() , nums.end());
for(int i = 0 ; i<n-1;i++){
if(nums[i] == nums[i+1]){
return nums[i];
}
}
return nums[n];
}
};
// alternative solution
class Solution {
public:
int findDuplicate(vector<int>& arr) {
int n = arr.size();
vector<int>freq(n+1 ,0);
for(int i = 0 ;i<n;i++){
if(freq[arr[i]]==0){
freq[arr[i]]++;
}else{
return arr[i];
}
}
return arr[n];
}
};
// alternative solution
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int slow = nums[0];
int fast = nums[0];
do{
slow = nums[slow];
fast = nums[nums[fast]];
}while(slow!= fast);
fast = nums[0];
while(slow!=fast){
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
};