File tree 2 files changed +25
-1
lines changed
algorithms/searchInsertPosition
2 files changed +25
-1
lines changed Original file line number Diff line number Diff line change 407
407
| 38| [ Count and Say] ( https://leetcode.com/problems/count-and-say/ ) | | Easy|
408
408
| 37| [ Sudoku Solver] ( https://leetcode.com/problems/sudoku-solver/ ) | | Hard|
409
409
| 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 |
411
411
| 34| [ Search for a Range] ( https://leetcode.com/problems/search-for-a-range/ ) | | Medium|
412
412
| 33| [ Search in Rotated Sorted Array] ( https://leetcode.com/problems/search-in-rotated-sorted-array/ ) | | Hard|
413
413
| 32| [ Longest Valid Parentheses] ( https://leetcode.com/problems/longest-valid-parentheses/ ) | | Hard|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments