題目
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
題目的意思是,在數組中找到指定元素的index,如果找不到,那麼返回它應該放置的正確index。
解答
我在SparseArray:解析與實現中剛好講解了這個算法的應用。
其實就是一個二分查找算法,找不到就返回low的取反就可以了。但由於題目的意思不需要我們區分找到找不到這個情況,只需要告訴我index,那麼就不需要取反了。
class Solution {
public int searchInsert(int[] nums, int target) {
int lo = 0;
int hi = nums.length - 1;
while (lo <= hi) {
final int mid = (lo + hi) >>> 1;
final int p = nums[mid];
if (p > target) {
hi = mid - 1;
} else if (p < target) {
lo = mid + 1;
} else {
return mid;
}
}
return lo;
}
}