leetcode 35. Search Insert Position

来源:互联网 发布:sn ty gm js是什么 编辑:程序博客网 时间:2024/05/19 02:26
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)     {        int l = 0;        int r = nums.size() - 1;        int mid;        while(l + 1 < r)        {            mid = l + (r - l) / 2;            if (nums[mid] == target)                return mid;            else if (nums[mid] < target)                l = mid;            else                r = mid;        }        //double check        if (nums[r] < target)            return r + 1;        else if (nums[l] < target && target <= nums[r])            return r;        else            return l;    }};


原创粉丝点击