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.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
一刷
题解:
结束时所在为mid, 如果num[mid] > target, 则hi = mid-1, 而num[mid-1]<target, 此时mid(lo)为插入位置,如果num[mid] < target, 则lo = mid+1,于是lo所在位置为插入位置。总之, lo为插入位置
public class Solution {
public int searchInsert(int[] nums, int target) {
int lo = 0, hi = nums.length-1, mid;
while(lo <= hi){
mid = lo + (hi - lo)/2;
if(nums[mid]>target) hi = mid-1;
else if(nums[mid] < target) lo = mid+1;
else return mid;
}
return lo;
}
}
二刷
思路同上
public class Solution {
public int searchInsert(int[] nums, int target) {
int lo = 0, hi = nums.length-1;
while(lo<=hi){
int mid = lo + (hi-lo)/2;
if(nums[mid]<target) lo = mid+1;
else if(nums[mid]>target) hi = mid-1;
else return mid;
}
return lo;
}
}