// 二分法 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 }) }
标签:pre,startIdx,return,target,nums,endIdx,数组,目标值,数字 From: https://www.cnblogs.com/zhenjianyu/p/17092739.html