forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
find-the-duplicate-number.cpp
76 lines (71 loc) · 1.72 KB
/
find-the-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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Time: O(n)
// Space: O(1)
// Two pointers method, same as Linked List Cycle II.
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int slow = nums[0];
int fast = nums[nums[0]];
while (slow != fast) {
slow = nums[slow];
fast = nums[nums[fast]];
}
fast = 0;
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
};
// Time: O(nlogn)
// Space: O(1)
// Binary search method.
class Solution2 {
public:
int findDuplicate(vector<int>& nums) {
int left = 1, right = nums.size();
while (left <= right) {
const int mid = left + (right - left) / 2;
// Get count of num <= mid.
int count = 0;
for (const auto& num : nums) {
if (num <= mid) {
++count;
}
}
if (count > mid) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}
};
// Time: O(n)
// Space: O(n)
class Solution3 {
public:
int findDuplicate(vector<int>& nums) {
int duplicate = 0;
// Mark the value as visited by negative.
for (auto& num : nums) {
if (nums[abs(num) - 1] > 0) {
nums[abs(num) - 1] *= -1;
} else {
duplicate = abs(num);
break;
}
}
// Rollback the value.
for (auto& num : nums) {
if (nums[abs(num) - 1] < 0) {
nums[abs(num) - 1] *= -1;
} else {
break;
}
}
return duplicate;
}
};