Leetcode解题报告:Search Insert Position

来源:互联网 发布:php 输出等边三角形 编辑:程序博客网 时间:2024/06/05 18:36

题目大意: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

难度:Medium

解题思路: 这道题属于二分查找问题,如果找到目标数则返回它的下标,否则就返回它应该被插入有序数组中的哪个位置下标。 二分查找的思路就是在有序数组中把处于中间位置的元素作为pivot,如果pivot大于目标数,则目标数只有可能在pivot左边,如果pivot小于目标数,则目标数只可能在pivot右边部分,否则pivot就是所要找的目标数。 如果找不到的话,再根据超出子范围的上界还是下界判断应当插入的位置是哪里,比如pivot比target大,应该搜索左边部分,但是mid-1<0,那么target应该插入位置0。当pivot比target大的时候,应该搜索右边部分,但是如果mid+1>end(end是右边边界),那么插入的位置就应该是end+1. 

这样算法的时间复杂度就是二分查找的时间复杂度O(logn)。

class Solution {public:int helper(vector<int> nums, int start,int end,int target){int  mid=(start+end)/2;if(nums[mid]==target){return mid;}else if(nums[mid]<target){    if(mid+1>end)    return end+1;    elsereturn helper(nums,mid+1,end,target);}else {    if(mid-1<0)    return 0;    elsereturn helper(nums,start,mid-1,target);}}int searchInsert(vector<int>& nums, int target) {    if(nums.size()==0)    return 0;else return helper(nums,0,nums.size()-1,target);}};

0 0