add: 寻找重复数
This commit is contained in:
parent
3770b30040
commit
6098f48863
@ -348,6 +348,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
|
||||
- LeetCode 146. LRU缓存机制 <https://leetcode-cn.com/problems/lru-cache/>
|
||||
- LintCode 134. LRU缓存策略 <https://www.lintcode.com/problem/lru-cache/description>
|
||||
|
||||
- [寻找重复数](src/array/find-the-duplicate-number.js)
|
||||
|
||||
- LeetCode 287. 寻找重复数 <https://leetcode-cn.com/problems/find-the-duplicate-number/>
|
||||
- LintCode 633. 寻找重复的数 <https://www.lintcode.com/problem/find-the-duplicate-number/description>
|
||||
|
||||
## 栈
|
||||
|
||||
- [最大矩阵](src/stack/maximal-rectangle.js)
|
||||
|
24
src/array/find-the-duplicate-number.js
Normal file
24
src/array/find-the-duplicate-number.js
Normal file
@ -0,0 +1,24 @@
|
||||
/**
|
||||
* @param {number[]} nums
|
||||
* @return {number}
|
||||
*/
|
||||
export const findDuplicate = function (nums) {
|
||||
const len = nums.length
|
||||
let l = 0; let r = len - 1; let res = -1 // 数字都在1-n
|
||||
while (l <= r) {
|
||||
const mid = (l + r) >> 1
|
||||
let cnt = 0
|
||||
for (let i = 0; i < len; i++) {
|
||||
cnt += nums[i] <= mid // true = 1,满足条件才计数
|
||||
}
|
||||
|
||||
if (cnt <= mid) {
|
||||
l = mid + 1
|
||||
} else {
|
||||
r = mid - 1
|
||||
res = mid
|
||||
}
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
6
test/array/find-the-duplicate-number.test.js
Normal file
6
test/array/find-the-duplicate-number.test.js
Normal file
@ -0,0 +1,6 @@
|
||||
import { findDuplicate } from '../../src/array/find-the-duplicate-number'
|
||||
|
||||
test('寻找重复数', () => {
|
||||
expect(findDuplicate([1, 3, 4, 2, 2])).toBe(2)
|
||||
expect(findDuplicate([3, 1, 3, 4, 2])).toBe(3)
|
||||
})
|
Loading…
Reference in New Issue
Block a user