File tree 2 files changed +17
-5
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder
2 files changed +17
-5
lines changed Original file line number Diff line number Diff line change @@ -4,13 +4,19 @@ public class _35 {
4
4
5
5
public static class Solution1 {
6
6
public int searchInsert (int [] nums , int target ) {
7
- int len = nums .length ;
8
- for (int i = 0 ; i < len ; i ++) {
9
- if (target <= nums [i ]) {
10
- return i ;
7
+ int left = 0 ;
8
+ int right = nums .length - 1 ;
9
+ while (left < right ) {
10
+ int mid = left + (right - left ) / 2 ;
11
+ if (nums [mid ] == target ) {
12
+ return mid ;
13
+ } else if (nums [mid ] < target ) {
14
+ left = mid + 1 ;
15
+ } else {
16
+ right = mid - 1 ;
11
17
}
12
18
}
13
- return len ;
19
+ return nums [ left ] >= target ? left : left + 1 ;
14
20
}
15
21
}
16
22
Original file line number Diff line number Diff line change @@ -20,4 +20,10 @@ public void test1() {
20
20
nums = new int []{1 , 3 , 5 , 6 };
21
21
assertEquals (2 , solution1 .searchInsert (nums , 5 ));
22
22
}
23
+
24
+ @ Test
25
+ public void test2 () {
26
+ nums = new int []{1 };
27
+ assertEquals (0 , solution1 .searchInsert (nums , 1 ));
28
+ }
23
29
}
You can’t perform that action at this time.
0 commit comments