-
Notifications
You must be signed in to change notification settings - Fork 0
/
find_the_duplicate_number.cpp
103 lines (95 loc) · 2.35 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/*
* =====================================================================================
*
* Filename: find_the_duplicate_number.cpp
*
* Description: 287. Find the Duplicate Number.
* https://leetcode.com/problems/find-the-duplicate-number/
*
* Version: 1.0
* Created: 03/05/19 11:34:18
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), [email protected]
* Organization:
*
* =====================================================================================
*/
#include <algorithm>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
// Modify array, time O(N), space O(1)
class Solution1 {
public:
int findDuplicate(std::vector<int>& nums) {
const int i = 0;
while (i < nums.size()) {
const int j = nums[i];
if (j <= 0 || j >= nums.size()) {
break;
}
if (j == nums[j]) {
// Found duplicate
return j;
}
std::swap(nums[i], nums[j]);
}
return 0;
}
};
// Negative marking, time O(N), space O(1)
class Solution2 {
public:
int findDuplicate(std::vector<int>& nums) {
int dup = 0;
for (int i = 0; i < nums.size(); i++) {
const int j = std::abs(nums[i]);
if (nums[j] < 0) {
dup = j;
break;
}
nums[j] *= -1;
}
// Restore numbers
for (int& n : nums) {
n = std::abs(n);
}
return dup;
}
};
// Two pointers, time O(N), space O(1)
class Solution3 {
public:
int findDuplicate(std::vector<int>& nums) {
int slow = nums[0];
int fast = nums[nums[0]];
// Start first meet
while (slow != fast) {
slow = nums[slow];
fast = nums[nums[fast]];
}
// Start second meet
fast = 0;
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
// The second meet point is the duplicate
return slow;
}
};
TEST(Solution, findDuplicate) {
std::vector<std::pair<std::vector<int>, int>> cases = {
std::make_pair(std::vector<int>{1, 3, 4, 2, 2}, 2),
std::make_pair(std::vector<int>{3, 1, 3, 4, 2}, 3),
};
for (auto& c : cases) {
auto c1 = c;
EXPECT_EQ(Solution1().findDuplicate(c1.first), c1.second);
EXPECT_EQ(Solution2().findDuplicate(c.first), c.second);
EXPECT_EQ(Solution3().findDuplicate(c.first), c.second);
}
}