查找相差最小的数字

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];
};

  

posted @ 2024-07-07 22:25  671_MrSix  阅读(7)  评论(0编辑  收藏  举报