forked from tangweikun/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
23 lines (22 loc) · 675 Bytes
/
index.ts
File metadata and controls
23 lines (22 loc) · 675 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
export function searchInsert(nums: number[], target: number) {
if (target < nums[0]) return 0
if (target > nums[nums.length - 1]) return nums.length
return binarySearch(nums, target, 0, nums.length - 1)
}
function binarySearch(
nums: number[],
target: number,
low: number,
high: number,
): number {
const mid = low + Math.floor((high - low) / 2)
while (low + 1 < high) {
if (nums[mid] === target) return mid
if (nums[mid] > target) return binarySearch(nums, target, low, mid)
return binarySearch(nums, target, mid, high)
}
// TODO: bug risk
if (nums[low] === target) return low
if (nums[high] === target) return high
return mid + 1
}