Skip to content

Commit bf6a425

Browse files
search insert position
1 parent 000093a commit bf6a425

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package chapter2_binary_search;
2+
3+
public class SearchInsertPosition {
4+
5+
/**
6+
* param A : an integer sorted array
7+
* param target : an integer to be inserted
8+
* return : an integer
9+
*/
10+
public static int searchInsert(int[] A, int target) {
11+
if(A == null || A.length == 0) return 0;
12+
// write your code here
13+
int left = 0, right = A.length-1;
14+
while(left+1 < right){
15+
int mid = left + (right-left)/2;
16+
if(A[mid] == target) return mid;
17+
else if(A[mid] > target) right = mid;
18+
else left = mid;
19+
}
20+
if(A[left] > target) return left == 0 ? 0 : left-1;
21+
if(A[right] < target) return right+1;
22+
else if(A[left] < target) return left+1;
23+
else if(A[left] == target) return left;
24+
else return right-1;
25+
}
26+
27+
public static void main(String...strings){
28+
// int[] A = new int[]{};
29+
// int target = 9;//should be 0
30+
31+
int[] A = new int[]{9,10,100,101,1002,10203};
32+
int target = 9;//should be 1
33+
System.out.println(searchInsert(A, target));
34+
}
35+
}

0 commit comments

Comments
 (0)