力扣打怪记002

力扣打怪记002

题目相关
数组
二分查找

题目链接

https://leetcode-cn.com/leetbook/read/array-and-string/cxqdh/

题目描述
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。

请必须使用时间复杂度为 O(log n) 的算法。

注意:
-104 <= nums[i] <= 104
nums 为无重复元素的升序排列数组
-104 <= target <= 104

心得
二分查找临界条件left<=right;
二分查找时间复杂度O(log n);
写得有点臃肿222

int searchInsert(int *nums, int numsSize, int target)
{
    int left = 0, right = numsSize - 1, center;
    while (left <= right)
    {
        center = (left + right) / 2;
        if (nums[center] > target)
        {
            right = center - 1;
            center = left;
        }
        if (nums[center] < target)
        {
            left = center + 1;
            center = right;
        }
        if (nums[center] == target)
            return center;
    }
    if (nums[center] < target)
        return center + 1;
    else
        return center;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值