关闭

Search Insert Position

33人阅读 评论(0) 收藏 举报
分类:

题目来源: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;
    }
};
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:187次
    • 积分:41
    • 等级:
    • 排名:千里之外
    • 原创:4篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档