leetcode 34. Find First and Last Position of Element in Sorted Array【裸二分】

https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int>ans;
        int l = 0, r = nums.size() - 1;
        if (r == -1){//不可以再忘记边界了!!!
            ans.push_back(-1);
            ans.push_back(-1);
            return ans;
        }
        while (l < r) {
            int mid = (l + r) >> 1;
            if (nums[mid] >= target)
                r = mid;
            else
                l = mid + 1;
        }
        if (nums[r] != target)
            ans.push_back(-1);
        else
            ans.push_back(r);
        l = 0, r = nums.size() - 1;
        while (l < r) {
            int mid = (l + r + 1) >> 1;//求小于等于或者小于某target通用的,因为是上限
            if (nums[mid] <= target)
                l = mid;
            else
                r = mid - 1;
        }
        if (nums[l] != target)
            ans.push_back(-1);
        else
            ans.push_back(l);
        return ans;
    }
};

 

全部评论

相关推荐

牛客868257804号:九个中铁八个中建
点赞 评论 收藏
分享
10-31 13:03
已编辑
重庆邮电大学 C++
hxd们,这是进池子的意思吗?
喜欢走神的孤勇者练习时长两年半:凯子今年舍得搞个网页查询了?我的评价是快跑
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务