Loading

【LBLD】我写了首诗,让你闭着眼睛也能写对二分搜索

我写了首诗,让你闭着眼睛也能写对二分搜索

704. 二分查找

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int left = 0, right = nums.size() - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                return mid;
            }
            else if (nums[mid] > target) {
                right = mid - 1;
            }
            else if (nums[mid] < target) {
                left = mid + 1;
            }
        }
        return -1;
    }
};

34. 在排序数组中查找元素的第一个和最后一个位置

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int leftBound = -1, rightBound = -1;
        // Left Bound
        int left = 0, right = nums.size();
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                right = mid;
            }
            else if (nums[mid] < target) {
                left = mid + 1;
            }
            else if (nums[mid] > target) {
                right = mid;
            }
        }
        if (left == nums.size()) leftBound = -1;
        else leftBound = nums[left] == target ? left : -1;
        // Right Bound
        left = 0, right = nums.size();
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                left = mid + 1;
            }
            else if (nums[mid] < target) {
                left = mid + 1;
            }
            else if (nums[mid] > target) {
                right = mid;
            }
        }
        if (left == 0) rightBound = -1;
        else rightBound = nums[left-1] == target ? left-1 : -1;

        return {leftBound, rightBound};
    }
};
posted @ 2023-04-14 11:13  杨谖之  阅读(11)  评论(0编辑  收藏  举报