LeetCode(55) Search Insert Position

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/angelazy/article/details/48687617

题目描述

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], 52
[1,3,5,6], 21
[1,3,5,6], 74
[1,3,5,6], 00

本题是查找一个有序数列中是否存在待查找的数字,若存在则返回该数字的位置,若不存在则返回该数字应该存在的位置。

解题思路

因为是有序数列所以可以使用二分查找的方法,不同于普通的二分查找,这里需要处理查找不到数字对应位置的问题。

class Solution {
public:

    int binarySearch(vector<int>& nums, int target, int begin, int end)
    {
        if(target < nums[begin])
            return begin;
        if(target > nums[end-1])
            return end;

        int mid = (begin+end)/2;
        if(target == nums[mid])
            return mid;
        else if(target < nums[mid])
            return binarySearch(nums, target, begin, mid);
        else
            return binarySearch(nums, target, mid, end);
    }
    int searchInsert(vector<int>& nums, int target) {
        return binarySearch(nums, target, 0, nums.size());
    }
};

猜你喜欢

转载自blog.csdn.net/angelazy/article/details/48687617