Leetcode解题报告: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.

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;
	    else
		return helper(nums,mid+1,end,target);
	}
	else 
	{
	    if(mid-1<0)
	    return 0;
	    else
		return 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);
}

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值