Skip to content

Commit 2f11fff

Browse files
committed
22w3: add 35 js solution
1 parent 876e916 commit 2f11fff

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -407,7 +407,7 @@
407407
|38|[Count and Say](https://leetcode.com/problems/count-and-say/)| |Easy|
408408
|37|[Sudoku Solver](https://leetcode.com/problems/sudoku-solver/)| |Hard|
409409
|36|[Valid Sudoku](https://leetcode.com/problems/valid-sudoku/)| |Easy|
410-
|35|[Search Insert Position](https://leetcode.com/problems/search-insert-position/)| |Medium|
410+
|35|[Search Insert Position](https://leetcode.com/problems/search-insert-position/)| [js](./algorithms/searchInsertPosition/solution.js) |Easy|
411411
|34|[Search for a Range](https://leetcode.com/problems/search-for-a-range/)| |Medium|
412412
|33|[Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/)| |Hard|
413413
|32|[Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/)| |Hard|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} target
4+
* @return {number}
5+
*/
6+
var searchInsert = function (nums, target) {
7+
// target 在左闭右闭的区间里,[left, right]
8+
let left = 0,
9+
right = nums.length - 1,
10+
result = nums.length;
11+
12+
// 因为题目要求时间复杂度是O(log n),所以得使用二分查找法
13+
while (left <= right) {
14+
const middle = left + Math.floor((right - left) >> 1);
15+
if (target > nums[middle]) {
16+
left = middle + 1; // target在右区间
17+
} else {
18+
result = middle; // target在左区间
19+
right = middle - 1;
20+
}
21+
}
22+
23+
return result;
24+
};

0 commit comments

Comments
 (0)