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
一刷
題解:
結(jié)束時(shí)所在為mid, 如果num[mid] > target, 則hi = mid-1, 而num[mid-1]<target, 此時(shí)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;
}
}