forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchInsertPosition.java
More file actions
27 lines (21 loc) · 675 Bytes
/
SearchInsertPosition.java
File metadata and controls
27 lines (21 loc) · 675 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
import java.util.Arrays;
public class SearchInsertPosition {
public int searchInsert(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (target == nums[mid]) {
return mid;
} else if (target > nums[mid]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;
}
public int searchInsert2(int[] nums, int target) {
int index = Arrays.binarySearch(nums, 0, nums.length, target);
return index >= 0 ? index : -(index + 1);
}
}