Search Insert Position

题目来源:https://leetcode.com/problems/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

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        // 处理特殊情况,nums为空和target小于最小的或者大于最大的数
        if(nums.empty() || target < nums[0])
            return 0;
        int numsSize = nums.size();
        if(nums[numsSize - 1] < target)
            return numsSize;
        int left = 0, mid, right = numsSize - 1;
        while(left < right - 1) {
            mid = (left + right) / 2;
            if(nums[mid] > target)
                right = mid;
            else if(nums[mid] < target)
                left = mid;
            else
                return mid;
        }
        if(nums[left] == target)
            return left;
        return right;
    }
};
阅读更多
个人分类: LeetCode原创
上一篇Search for a Range
下一篇Best Time to Buy and Sell Stock IV(DP解法,o(kn)时间,o(k)空间)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭