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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jsszwc/article/details/87657116

题目:

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

题意:

给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。

你的算法时间复杂度必须是 O(log n) 级别。

如果数组中不存在目标值,返回 [-1, -1]。

思路:

O ( l o g n ) O(logn) 的算法,显然是用二分法确定首尾,注意检查没有解的情况。二分可以自己实现,也可以直接用 S T L STL l o w e r _ b o u n d lower\_bound u p p e r _ b o u n d upper\_bound

代码:

STL版二分

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int l = lower_bound(nums.begin(), nums.end(), target) - nums.begin();
        int r = upper_bound(nums.begin(), nums.end(), target) - nums.begin();
        if(l == nums.size() || nums[l] != target)
            l = -1;
        if(r == 0 || nums[r-1] != target)
            r = -1;
        else
            r -= 1;

        return vector<int>{l, r};
    }
};

自行实现二分

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int l = binaryL(nums, target);
        int r = binaryR(nums, target);
        if(l == nums.size() || nums[l] != target)
            l = -1;
        if(r == 0 || nums[r-1] != target)
            r = -1;
        else 
            r -= 1;
        return vector<int>{l, r};
    }

    int binaryL(vector<int> &nums, int target) {
        int l = 0, r = int(nums.size()) - 1;
        int ans = nums.size();
        while(l <= r) {
            int mid = (l + r) >> 1;
            if(nums[mid] >= target) {
                r = mid - 1;
                ans = mid;
            } else{
                l = mid + 1;
            }
        }
        return ans;
    }

    int binaryR(vector<int> &nums, int target) {
        int l = 0, r = int(nums.size()) - 1;
        int ans = nums.size();
        while(l <= r) {
            int mid = (l + r) >> 1;
            if(nums[mid] > target) {
                r = mid - 1;
                ans = mid;
            } else {
                l = mid + 1;
            }
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/jsszwc/article/details/87657116