35. Search Insert Position

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;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容