[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;
    }
};

猜你喜欢

转载自blog.csdn.net/annazzz/article/details/83069453