Skip to content

Commit 67ca04a

Browse files
committed
solve problem Find The Duplicate Number
1 parent 28bcec1 commit 67ca04a

File tree

5 files changed

+67
-0
lines changed

5 files changed

+67
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,7 @@ All solutions will be accepted!
258258
|56|[Merge Intervals](https://leetcode-cn.com/problems/merge-intervals/description/)|[java/py/js](./algorithms/MergeIntervals)|Medium|
259259
|11|[Container With Most Water](https://leetcode-cn.com/problems/container-with-most-water/description/)|[java/py/js](./algorithms/ContainerWithMostWater)|Medium|
260260
|338|[Counting Bits](https://leetcode-cn.com/problems/counting-bits/description/)|[java/py/js](./algorithms/CountingBits)|Medium|
261+
|287|[Find The Duplicate Number](https://leetcode-cn.com/problems/find-the-duplicate-number/description/)|[java/py/js](./algorithms/FindTheDuplicateNumber)|Medium|
261262

262263
# Database
263264
|#|Title|Solution|Difficulty|
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Find The Duplicate Number
2+
We can solve this problem by Binary Search
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution {
2+
public int findDuplicate(int[] nums) {
3+
int low = 1,
4+
high = nums.length - 1;
5+
6+
while (low < high) {
7+
int mid = (low + high) / 2,
8+
count = 0;
9+
10+
for (int n : nums)
11+
count += n <= mid ? 1 : 0;
12+
13+
if (count > mid) {
14+
high = mid;
15+
} else {
16+
low = mid + 1;
17+
}
18+
}
19+
20+
return low;
21+
}
22+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
var findDuplicate = function(nums) {
6+
let low = 1,
7+
high = nums.length - 1
8+
9+
while (low < high) {
10+
let mid = parseInt((low + high) / 2),
11+
count = 0
12+
13+
nums.forEach(n => count += (n <= mid ? 1 : 0))
14+
15+
if (count > mid) {
16+
high = mid
17+
} else {
18+
low = mid + 1
19+
}
20+
}
21+
22+
return low
23+
};
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution(object):
2+
def findDuplicate(self, nums):
3+
"""
4+
:type nums: List[int]
5+
:rtype: int
6+
"""
7+
low = 1
8+
high = len(nums) - 1
9+
10+
while low < high:
11+
mid = (low + high) / 2
12+
count = sum(x <= mid for x in nums)
13+
14+
if count > mid:
15+
high = mid
16+
else:
17+
low = mid + 1
18+
19+
return low

0 commit comments

Comments
 (0)