Skip to content

Commit 06198ab

Browse files
committed
featt: add binary search insert
1 parent 5a27205 commit 06198ab

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

js/binary_search_insert.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/*
2+
* @Author: Chacha
3+
* @Date: 2022-05-14 15:02:58
4+
* @Last Modified by: Chacha
5+
* @Last Modified time: 2022-05-14 15:04:12
6+
*/
7+
8+
// https://leetcode-cn.com/problems/search-insert-position/
9+
// 35. 搜索插入位置
10+
11+
const binarySearchInsert = (nums, target) => {
12+
let i = 0;
13+
let j = nums.length - 1;
14+
let midIndex = 0;
15+
16+
while (i <= j) {
17+
midIndex = Math.floor((i + j) / 2);
18+
const midValue = nums[midIndex];
19+
20+
if (midValue === target) {
21+
return midIndex;
22+
} else if (midValue < target) {
23+
i = midIndex + 1;
24+
} else {
25+
j = midIndex - 1;
26+
}
27+
}
28+
29+
return i;
30+
};
31+
32+
console.log(binarySearchInsert([1, 3, 5, 6], 7));

0 commit comments

Comments
 (0)