Leetcode 287. Find the Duplicate Number

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Find the Duplicate Number

2. Solution

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int n = nums.size();
for(int i = 0; i < n; i++) {
for(int j = i + 1; j < n; j++) {
if((nums[i] ^ nums[j]) == 0) {
return nums[i];
}
}
}
}
};
  • Version 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int i = 0;
int j = 0;
while(true) {
i = nums[i];
j = nums[nums[j]];
if(i == j) {
break;
}
}
i = 0;
while(true) {
i = nums[i];
j = nums[j];
if(i == j) {
return i;
}
}
}
};
  • Version 3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int low = 1;
int high = nums.size() - 1;
while(low < high) {
int mid = (low + high) / 2;
int count = 0;
for(int i = 0; i < nums.size(); i++) {
if(nums[i] <= mid) {
count++;
}
}
if(count <= mid) {
low = mid + 1;
}
else {
high = mid;
}
}
return low;
}
};

Reference

  1. https://leetcode.com/problems/find-the-duplicate-number/description/
如果有收获,可以请我喝杯咖啡!