从零开始的LC刷题(11): 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.

Example 1:

Input: [1,3,5,6], 5
Output: 2

Example 2:

Input: [1,3,5,6], 2
Output: 1

Example 3:

Input: [1,3,5,6], 7
Output: 4

Example 4:

Input: [1,3,5,6], 0
Output: 0

其实就是个二分查找但是如果未找到要返回插入位置的索引,先用递归实现,结果如下:

Success

Runtime: 8 ms, faster than 98.57% of C++ online submissions for Search Insert Position.

Memory Usage: 8.8 MB, less than 98.32% of C++ online submissions for Search Insert Position.

代码:

class Solution {
public:
    int searchInsert(vector& nums, int target) {
        return Bsearch(nums,target,0,nums.size()-1);
    }
    int Bsearch(vector& nums,int target,int l,int r){
        if (nums[(l+r)/2]==target){return (l+r)/2;}
        if(l>=r){if(nums[l]>target){return l;}
                else return l+1;}
        else if(nums[(l+r)/2]>target){return Bsearch(nums,target,l,(l+r)/2-1);}
        else if(nums[(l+r)/2]

 

也可以循环实现,结果一样,代码:

class Solution {
public:
    int searchInsert(vector& nums, int target) {
        int l=0,r=nums.size()-1,m=0;
        while(l<=r){
            m=(l+r)/2;
            if (nums[m]==target){return m;}
            else if(nums[m]>target){r=m-1;continue;}
            else{l=m+1;}
        }
        return l;
    }
};

 

你可能感兴趣的:(LEETCODE,C++)