每日两题 / 34. 在排序数组中查找元素的第一个和最后一个位置 && 33. 搜索旋转排序数组(LeetCode热题100)

发布于:2024-06-04 ⋅ 阅读:(46) ⋅ 点赞:(0)

34. 在排序数组中查找元素的第一个和最后一个位置 - 力扣(LeetCode)
image.png

根据二分函数,得到>=target<=target的两个,分别是答案的l和r

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

33. 搜索旋转排序数组 - 力扣(LeetCode)
image.png

先确定两个有序区间的分界点,然后分别对两个区间进行二分
需要考虑数组长度为2,且旋转过的情况

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int l = 0, r = nums.size() - 1;
        int t = 0;
        if (*nums.begin() > *nums.rbegin()) {
            while (l < r) {
                int mid = (l + r) / 2;
                if (mid - 1 >= 0 && nums[mid] < nums[mid - 1]) {
                    t = mid;
                    break;
                }
                else if (mid + 1 < nums.size() && nums[mid] > nums[mid + 1]) {
                    t = mid + 1;
                    break;
                }
                else if (nums[mid] > nums[0]) l = mid;
                else if (nums[mid] < nums[0]) r = mid;
            }
        }
        if (t) {
            auto it = lower_bound(nums.begin(), nums.begin() + t, target);
            if (it != nums.end() && *it == target) return it - nums.begin();
            it = lower_bound(nums.begin() + t, nums.end(), target);
            if (it != nums.end() && *it == target) return it - nums.begin();
            else return -1;
        }
        else {
            auto it = lower_bound(nums.begin(), nums.end(), target);
            if (it != nums.end() && *it == target) return it - nums.begin();
            else return -1;
        }
    }
};

网站公告

今日签到

点亮在社区的每一天
去签到