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:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Example 3:
Input: [1,3,5,6], 7
Output: 4
Example 4:
Input: [1,3,5,6], 0
Output: 0
Solution
- 根据二分法找target,如果找到则直接返回index
- 没有找到,则需要根据start和end的值,来判断index的值。
- 需要注意,example4中,如果target比index == 0的数还小时,此时返回的index就应该是0, 额入市start - 1.
class Solution {
public int searchInsert(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return -1;
}
int start = 0;
int end = nums.length - 1;
while (start + 1 < end) {
int middle = start + (end - start) / 2;
if (target == nums [middle]) {
return middle;
}
if (target > nums [middle]) {
start = middle;
} else {
end = middle;
}
}
if (target == nums [start])
return start;
if (target == nums [end])
return end;
// cannot find the target, then need to decide its order index
if (target > nums [start] && target < nums [end]) {
return start + 1;
} else if (target > nums [end]) {
return end + 1;
} else if (target < nums [start]) {
return start == 0 ? start : start - 1;
}
return -1;
}
}