题目
- 找出数组中重复的数字。
- 在一个长度为 n+1 的数组 nums 里的所有数字都在 1~n 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。不能修改原数组,请找出数组中任意一个重复的数字。
- 示例 1:
- 输入:[2, 3, 5, 3, 2, 6, 7]
- 输出:2 或 3
思路
- 二分查找的思想。对于每段数 如1-4、5-8,当在原数组中出现的次数大于他那一段的长度,则表示当前段有重复数字。详解看剑指OFFER原版解析
/**
* @param {number[]} nums
* @return {number}
* 时间复杂度:O(nlogn),空间复杂度:O(1)
*/
const getShowedCounts = (array, start, end) => {
let counts = 0
for (let i = 0; i < array.length; i++) {
if (array[i] >= start && array[i] <= end) {
counts++
}
}
return counts
}
const findRepeatNumber = function(nums) {
if (nums.length <= 1) {
return null
} else if (nums.length === 2) {
return nums[0] === nums[1] ? nums[0] : null
}
let start = 1
let end = nums.length - 1
while(start <= end) {
const middle = ((end - start) >> 1) + start
const counts = getShowedCounts(nums, start, middle)
if (start === end) {
if (counts > 1) {
return start
} else {
return null
}
}
if (counts > (middle - start + 1)) {
end = middle
} else {
start = middle + 1
}
}
return null
}
const test_array = [2, 3, 5, 3, 2, 6, 7]
console.log(findRepeatNumber(test_array))