数组中找到与目标值最接近的数字

// 二分法 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
    })
} 

  

posted @ 2023-02-05 00:58  671_MrSix  阅读(125)  评论(0编辑  收藏  举报