Files
js-practice/src/array/find-the-duplicate-number.js
2020-05-26 23:27:04 +08:00

25 lines
473 B
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @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
}