add: 寻找重复数

This commit is contained in:
yi-ge 2020-05-26 23:27:04 +08:00
parent 3770b30040
commit 6098f48863
3 changed files with 35 additions and 0 deletions

View File

@ -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)

View 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
}

View 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)
})