Skip to content

Latest commit

 

History

History
38 lines (33 loc) · 872 Bytes

在排序数组中查找元素的第一个和最后一个位置.md

File metadata and controls

38 lines (33 loc) · 872 Bytes
function binarySearvch(nums, target, flag) {
  let left = 0,
    right = nums.length - 1,
    ans = nums.length;

  while (left <= right) {
    let mid = Math.floor((left + right) / 2);

    if (nums[mid] > target || (flag && nums[mid] >= target)) {
      right = mid - 1;
      ans = mid;
    } else {
      left = mid + 1;
    }
  }

  return ans;
}

function searchRange(nums, target) {
  let res = [-1, -1];
  let left = binarySearvch(nums, target, true);
  let right = binarySearvch(nums, target, false) - 1;
  //  合法性判断
  if (
    left <= right &&
    right < nums.length &&
    nums[left] === target &&
    nums[right] === target
  ) {
    return [left, right];
  }
  return res;
}