数组中找到与目标值最接近的数字
// 二分法 O(logn)
const findNearestTarget = (nums = [1, 2, 6, 9, 10], target = 3) => {
let startIdx = 0,
endIdx = nums.length - 1;
while (startIdx <= endIdx) {
let midIdx = Math.floor((startIdx + endIdx) / 2)
if (nums[midIdx] > target) {
endIdx = --midIdx
} else if (nums[midIdx] < target) {
startIdx = ++midIdx
} else {
return target
}
}
return target - nums[startIdx] > nums[endIdx] - target ? nums[startIdx] : nums[endIdx]
}
// reduce O(n)
const findNearestTarget = (nums = [1, 2, 6, 9, 10], target = 3) => {
return nums.reduce((pre, cur) => {
return Math.abs(pre - target) > Math.abs(cur - target) ? cur : pre
})
}
以自己现在的努力程度,还没有资格和别人拼天赋

浙公网安备 33010602011771号