35 Search Insert Position

1. Question

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.
You may assume no duplicates in the array.
Example 1:
1
Input: [1,3,5,6], 5
2
3
Output: 2
Copied!
Example 2:
1
Input: [1,3,5,6], 2
2
3
Output: 1
Copied!
Example 3:
1
Input: [1,3,5,6], 7
2
3
Output: 4
Copied!
Example 4:
1
Input: [1,3,5,6], 0
2
3
Output: 0
Copied!

2. Implementation

思路: 这题相当于找到一个数x >= target, 属于二分法找x左边界的问题
(1) Binary Search
1
class Solution {
2
public int searchInsert(int[] nums, int target) {
3
int start = 0, end = nums.length - 1, mid = 0;
4
5
while (start + 1 < end) {
6
mid = start + (end - start) / 2;
7
8
if (nums[mid] < target) {
9
start = mid + 1;
10
}
11
else {
12
end = mid;
13
}
14
}
15
16
if (nums[start] >= target) {
17
return start;
18
}
19
else if (nums[end] >= target) {
20
return end;
21
}
22
else {
23
return nums.length;
24
}
25
}
26
}
Copied!

3. Time & Space Complexity

Binary Search:时间复杂度O(logn),n是nums的长度, 空间复杂度O(1)