Skip to content

Commit 8068915

Browse files
committedSep 19, 2023
feat: solve No.287
1 parent 6207602 commit 8068915

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed
 
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
# 287. Find the Duplicate Number
2+
3+
- Difficulty: Medium.
4+
- Related Topics: Array, Two Pointers, Binary Search, Bit Manipulation.
5+
- Similar Questions: First Missing Positive, Single Number, Linked List Cycle II, Missing Number, Set Mismatch.
6+
7+
## Problem
8+
9+
Given an array of integers `nums` containing `n + 1` integers where each integer is in the range `[1, n]` inclusive.
10+
11+
There is only **one repeated number** in `nums`, return **this repeated number**.
12+
13+
You must solve the problem **without** modifying the array `nums` and uses only constant extra space.
14+
15+
 
16+
Example 1:
17+
18+
```
19+
Input: nums = [1,3,4,2,2]
20+
Output: 2
21+
```
22+
23+
Example 2:
24+
25+
```
26+
Input: nums = [3,1,3,4,2]
27+
Output: 3
28+
```
29+
30+
 
31+
**Constraints:**
32+
33+
34+
35+
- `1 <= n <= 105`
36+
37+
- `nums.length == n + 1`
38+
39+
- `1 <= nums[i] <= n`
40+
41+
- All the integers in `nums` appear only **once** except for **precisely one integer** which appears **two or more** times.
42+
43+
44+
 
45+
**Follow up:**
46+
47+
48+
49+
- How can we prove that at least one duplicate number must exist in `nums`?
50+
51+
- Can you solve the problem in linear runtime complexity?
52+
53+
54+
55+
## Solution 1
56+
57+
```javascript
58+
/**
59+
* @param {number[]} nums
60+
* @return {number}
61+
*/
62+
var findDuplicate = function(nums) {
63+
var left = 0;
64+
var right = nums.length - 1;
65+
while (left < right) {
66+
var mid = left + Math.floor((right - left) / 2);
67+
var num = getNum(nums, mid);
68+
if (num <= mid) {
69+
left = mid + 1;
70+
} else {
71+
right = mid;
72+
}
73+
}
74+
return left;
75+
};
76+
77+
var getNum = function(nums, n) {
78+
var num = 0;
79+
for (var i = 0; i < nums.length; i++) {
80+
if (nums[i] <= n) num++;
81+
}
82+
return num;
83+
};
84+
```
85+
86+
**Explain:**
87+
88+
nope.
89+
90+
**Complexity:**
91+
92+
* Time complexity : O(n * log(n)).
93+
* Space complexity : O(1).

0 commit comments

Comments
 (0)