Skip to content

35. 搜索插入位置

35. 搜索插入位置

代码

javascript
// 35. 搜索插入位置:https://leetcode.cn/problems/search-insert-position/description/
// 输入:nums = [1,3,5,6], target = 5
// 输出:2

export function searchInsertPosition (nums, target) {
  let low = 0
  let high = nums.length - 1
  while (low <= high) {
    let mid = low + Math.floor((high - low) / 2)
    if (nums[mid] === target) {
      return mid
    } else if (nums[mid] < target) {
      low = mid + 1
    } else {
      high = mid - 1
    }
  }

  return high + 1
}
typescript
// 35. 搜索插入位置:https://leetcode.cn/problems/search-insert-position/description/
// 输入:nums = [1,3,5,6], target = 5
// 输出:2

export function searchInsertPosition (nums: number[], target: number): number {
  let low = 0
  let high = nums.length - 1
  while (low <= high) {
    let mid = low + Math.floor((high - low) / 2)
    if (nums[mid] === target) {
      return mid
    } else if (nums[mid] < target) {
      low = mid + 1
    } else {
      high = mid - 1
    }
  }

  return high + 1
}

测试代码

ts
import { expect, test } from 'vitest'
import { searchInsertPosition } from './typescript.ts'
import { searchInsertPosition as searchInsertPositionJs } from './javascript.js'

test(`searchInsertPosition`, () => {
  expect(searchInsertPosition([1,3,5,6], 5)).toBe(2)
  expect(searchInsertPosition([1,3,5,6], 2)).toBe(1)
  expect(searchInsertPosition([1,3,5,6], 7)).toBe(4)
  expect(searchInsertPosition([1,3,5,6], 4)).toBe(2)
})

test(`searchInsertPositionJs`, () => {
  expect(searchInsertPositionJs([1,3,5,6], 5)).toBe(2)
  expect(searchInsertPositionJs([1,3,5,6], 2)).toBe(1)
  expect(searchInsertPositionJs([1,3,5,6], 7)).toBe(4)
  expect(searchInsertPositionJs([1,3,5,6], 4)).toBe(2)
})