日野弥生:勉強しよう

LeetCode 35 - 搜索插入位置

发表于2024年12月12日

#数组 #二分法 #二分查找

利用非递归的方法进行二分查找。需要注意临界状态(start <=end)、以及利用左移运算对mid做向下取整。

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int end = nums.size()-1,start=0;

        while(start <=end)
        {
        int mid = start + ((end - start) >> 1);
        if(target<nums[mid])
            end =mid-1;
        else if(target>nums[mid])
            start = mid+1;
        else 
            return mid;
        }
        return start;
    }
};

フラッシュタブ:LeetCode

题目链接:https://leetcode.cn/problems/search-insert-position/

上一篇

LeetCode 1991 - 找到数组的中间位置

下一篇

LeetCode 56 - 合并区间