Skip to content

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

  • 题号:34
  • 来源:LeetCode
  • 难度:中等
  • 标签:二分 数组
  • 语言:TypeScript
  • 解法:1 个
  • 作者:lmliheng
  • 最近更新:2026-09-27

TypeScript · O(log n) 时间 · O(1) 空间 · 更新于 2026-09-27

两次 lowerBound 分别求左右边界

typescript
/**
 * @difficulty medium
 * @tags 二分,数组
 * @time O(log n)
 * @space O(1)
 * @note 两次 lowerBound 分别求左右边界
 * @34. 在排序数组中查找元素的第一个和最后一个位置
 */

import { lowerBound } from "../算法/二分查找/二分查找.js";

function searchRange(nums: number[], target: number) {
    let index1 = lowerBound((mid) => nums[mid] >= target, 0, nums.length)
    let index2 = lowerBound((mid) => nums[mid] > target, 0, nums.length)
    if (index1 == nums.length || nums[index1] !== target) {
        return [-1, -1]
    }

    return [index1, index2 - 1]
};

源码:ts/leetcode/34. 在排序数组中查找元素的第一个和最后一个位置.ts


在 GitHub 上查看题目所在目录:lmliheng/algorithm