-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSearchInsertPos.java
More file actions
45 lines (30 loc) · 999 Bytes
/
Copy pathSearchInsertPos.java
File metadata and controls
45 lines (30 loc) · 999 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* leetcode: https://leetcode.com/problems/search-insert-position/
*/
public class SearchInsertPos{
public static int binarySearch(int[] nums, int left, int right, int target) {
if (left > right) {
return left;
}
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return mid;
}
else if (nums[mid] > target) {
return binarySearch(nums, left, mid - 1, target);
} else {
return binarySearch(nums, mid + 1, right, target);
}
}
public static int searchInsert(int[] nums, int target) {
if(nums.length == 0) {
return 0;
}
return binarySearch(nums, 0, nums.length -1, target);
}
public static void main(String[] args) {
assert searchInsert(new int[]{1, 3, 5, 6}, 5) == 2;
assert searchInsert(new int[]{1, 3, 5, 6}, 2) == 1;
assert searchInsert(new int[]{1, 3, 5, 6}, 0) == 0;
}
}