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;
}
}