力扣打怪记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;
}

上一篇:【ssl 1232】【叉积】雷达覆盖


下一篇:android获取时间戳接口