1. 程式人生 > >[leetcode]35. Search Insert Position

[leetcode]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.

思路:
直接用二分法搜尋關鍵字即可,利用二分法的low<=high特點,若nums[mid]==target則返回mid;否則返回left即可。
註釋中的是我一開始寫的方法,多此一舉了。

實現程式碼(C++):

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int low = 0;
        int high = nums.size()-1;
        int mid = 0;
        
        while(low<=high){
            mid = (low+high)/2;
            if(nums[mid]==target){
                return mid;
            }
            else if(nums[mid]<target){
                /*
                if(nums[mid+1]>target || mid==nums.size()-1){
                    return mid+1;
                }
                */
                low = mid+1;
            }
            else if(nums[mid]>target){
                /*
                if(nums[mid-1]<target || mid==0){
                    return mid;
                }
                */
                high = mid-1;
            }
        }
        return low;
    }
};