const findClosestNumbers = (arr = [1, 2, 3, 4, 5, 6, 7, 8, 9], target = 3) => { let left = 0; let right = arr.length - 1; let minDiff = Infinity; let closestNumbers = []; while (left <= right) { const mid = Math.floor((left + right) / 2); const diff = Math.abs(arr[mid] - target); if (diff < minDiff) { minDiff = diff; closestNumbers = [arr[mid]]; } else if (diff === minDiff) { closestNumbers.push(arr[mid]); } if (arr[mid] === target) { break; } else if (arr[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return closestNumbers; };
const findClosestNumbers = (arr = [1, 2, 3, 4, 5, 6, 7, 8, 9], target = 3) => { const map = []; arr.forEach((item) => { const diff = Math.abs(item - target); if (!map[diff]) { map[diff] = []; } map[diff].push(item); }); return map[0] || map[map.findIndex((item) => !item) + 1]; };
标签:map,arr,相差,最小,item,查找,let,diff,const From: https://www.cnblogs.com/zhenjianyu/p/18289040