[leetcode][search] Search Insert Position

来源:互联网 发布:美国时装画技法淘宝 编辑:程序博客网 时间:2024/06/06 11:39

题目:

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


class Solution {public:    int searchInsert(vector<int>& nums, int target) {        if(nums.empty()) return 0;        return searchInsertCore(nums, 0, nums.size()-1, target);    }private:    int searchInsertCore(vector<int>& nums, int start, int end, int target){       if (start == end) return target <= nums[start] ? start : start+1;//!!!根据当前值和target的大小确定返回位置        int mid = (start+end) >> 1;        if(target == nums[mid]) return mid;        if(target > nums[mid]) return searchInsertCore(nums, mid+1, end, target);        else return searchInsertCore(nums, start, mid, target);//如果start==mid,下次递归就会返回,不用mid-1,是为了防止越界,而且这样处理之后永远不会出现start>end的情况    }};


0 0
原创粉丝点击