Skip to content

Commit 1b35edf

Browse files
committed
Search Insert Position
1 parent 75b41a8 commit 1b35edf

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Search Insert Position.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
2+
3+
You may assume no duplicates in the array.
4+
5+
Here are few examples.
6+
[1,3,5,6], 5 ¡ú 2
7+
[1,3,5,6], 2 ¡ú 1
8+
[1,3,5,6], 7 ¡ú 4
9+
[1,3,5,6], 0 ¡ú 0
10+
11+
public class Solution {
12+
public int searchInsert(int[] A, int target) {
13+
return search(A, target, 0, A.length - 1);
14+
}
15+
16+
private int search(int[] A, int target, int l, int r) {
17+
int mid = 0;
18+
while (l <= r) {
19+
mid = (l + r) / 2;
20+
if (A[mid] == target) {
21+
return mid;
22+
} else if (A[mid] < target) {
23+
if (mid == A.length - 1) {
24+
return mid + 1;
25+
} else if (A[mid + 1] > target) {
26+
return mid + 1;
27+
} else {
28+
l = mid + 1;
29+
}
30+
} else if (A[mid] > target) {
31+
if (mid == 0) {
32+
return mid;
33+
} else if (A[mid - 1] < target) {
34+
return mid;
35+
} else {
36+
r = mid - 1;
37+
}
38+
}
39+
}
40+
return 0;
41+
}
42+
}

0 commit comments

Comments
 (0)