编程训练第十三期——在排序数组中查找元素的第一个和最后一个位置

编程问题:

给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。如果数组中不存在目标值 target,返回 [-1, -1]。要求时间复杂度为 O(log n)


示例:

  • 输入:nums = [5,7,7,8,8,10], target = 8
    输出:[3,4]
  • 输入:nums = [5,7,7,8,8,10], target = 6
    输出:[-1,-1]
  • 输入:nums = [], target = 0
    输出:[-1,-1]

解法:

1.二分查找
时间复杂度O(log N)
空间复杂度O(1)

class Solution {
private:
    int binarySearch(vector<int>& nums, int n, int target, bool location) 
    {
        int left = 0, right = n - 1;
        while (left < right) 
        {
            if(location) //寻找开始位置
            {
                int mid = (left + right) / 2;
                if (nums[mid] >= target) 
                {
                    right = mid; 
                }
                else
                {
                    left = mid + 1;
                }
            }
            else     //寻找结束位置
            {
                int mid = (left + right + 1) / 2;
                if (nums[mid] <= target)
                {
                    left = mid;
                }
                else
                {
                    right = mid - 1;
                }
            }
        }
        return right;
    }

public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int n = nums.size();
        vector<int> res;
        if (n == 0) return {-1, -1};
        int leftIndex = binarySearch(nums, n, target, true);
        if (nums[leftIndex] != target) 
        {
            return {-1, -1};
        }
        res.push_back(leftIndex);
        int rightIndex = binarySearch(nums, n, target, false);
        res.push_back(rightIndex);

        return res;
    }
};

你可能感兴趣的:(算法)