-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathLC_287_FindDuplicateNumber.cpp
66 lines (53 loc) · 1.36 KB
/
LC_287_FindDuplicateNumber.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
61
62
63
64
65
66
/*
https://leetcode.com/problems/find-the-duplicate-number/
287. Find the Duplicate Number
*/
class Solution {
public:
int findDuplicate(vector<int>& nums) {
/*
sort(nums.begin(), nums.end());
for(int i=1; i<nums.size(); i++)
{
if(nums[i-1]==nums[i])
return nums[i];
}
return -1;
*/
/*
set<int> s;
for(int i=0; i<nums.size(); i++)
{
if(s.find(nums[i]) == s.end())
s.insert(nums[i]);
else
return nums[i];
}
return -1;
*/
// /Floyd's Tortoise and Hare
// int slow = nums[0];
// int fast = nums[0];
// do
// {
// slow = nums[slow];
// fast = nums[nums[fast]];
// }while(slow!=fast);
// // find the exact location
// slow = nums[0];
// while(slow!=fast)
// {
// slow = nums[slow];
// fast = nums[fast];
// }
// return fast;
for(int i=0; i<nums.size(); i++)
{
int ind = abs(nums[i]);
if(nums[ind] < 0)
return ind;
nums[ind]*=-1;
}
return -1;
}// end
};