File tree Expand file tree Collapse file tree 1 file changed +21
-13
lines changed
Algorithms Basics/Chapter 6. Binary Search Expand file tree Collapse file tree 1 file changed +21
-13
lines changed Original file line number Diff line number Diff line change
1
+ // keynote:
2
+ // 1. start from boundary checking
3
+ // 2. use simple real case to determine the index in the end
1
4
public class Solution {
2
5
public int SearchInsert ( int [ ] nums , int target ) {
3
- if ( nums == null || nums . Length == 0 ) return 0 ;
4
- int start = 0 ;
5
- int end = nums . Length - 1 ;
6
- while ( start + 1 < end ) {
7
- int mid = start + ( end - start ) / 2 ;
8
- if ( nums [ mid ] == target ) {
9
- return mid ;
10
- } else if ( nums [ mid ] < target ) {
11
- start = mid ;
6
+ if ( nums == null || nums . Length == 0 ) {
7
+ return 0 ;
8
+ }
9
+ int l = 0 , r = nums . Length - 1 , m ;
10
+ while ( l + 1 < r ) {
11
+ m = l + ( r - l ) / 2 ;
12
+ if ( nums [ m ] == target ) {
13
+ return m ;
14
+ } else if ( nums [ m ] < target ) {
15
+ l = m + 1 ;
12
16
} else {
13
- end = mid ;
17
+ r = m - 1 ;
14
18
}
15
19
}
16
- if ( target <= nums [ start ] ) return start ;
17
- if ( nums [ start ] < target && target <= nums [ end ] ) return end ;
18
- return end + 1 ;
20
+ if ( target <= nums [ l ] ) {
21
+ return l ;
22
+ }
23
+ if ( target > nums [ r ] ) {
24
+ return r + 1 ;
25
+ }
26
+ return r ;
19
27
}
20
28
}
You can’t perform that action at this time.
0 commit comments