[leetcode] 35. Search Insert Position

来源:互联网 发布:西西软件家园 编辑:程序博客网 时间:2024/05/16 01:10

Question:

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

Solution:

二分的升级版,要特别特别注意边界的情况就好。因为找不到也要返回应该出现的位置。

class Solution {public:    int searchInsert(vector<int>& nums, int target) {        int l = 0, mid, r = nums.size() - 1;        while (l <= r) {            mid = (l + r) / 2;            if (nums[mid] == target)                 return mid;            if (l == r) {                if (target < nums[l])                     return l;                if (l + 1 == nums.size() || target < nums[l + 1])                     return l + 1;                return l + 2;            }            if (nums[mid] < target) {                l = mid + 1;            } else {                r = mid;            }        }        return -1;    }};
原创粉丝点击