35. Search Insert Position

来源:互联网 发布:淘宝代销怎么联系卖家 编辑:程序博客网 时间:2024/05/07 07:14

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


思路:

(1)二分查找法,如果找到了target,就返回index.

(2)当l==r时,如果仍然没有找到,判断target 与 nums[l] 的大小,如果target < nums[l],则返回l的值;

         如果target > nums[l],则返回l+1的值。


代码:

int searchInsert(int* nums, int numsSize, int target) {    int l=0;    int r=numsSize-1;        while(l < r)    {        int m=(l+r)/2;        if(nums[m] == target ) return m;        else if(nums[m] > target ) r=m-1;        else if(nums[m] < target ) l=m+1;    }        if(l==r && nums[l]==target) return l;        if(nums[l] < target ) return l+1;    else return l;    }























0 0
原创粉丝点击