leetcode笔记:Search for a Range

一. 题目描述

Given a sorted array of integers, find the starting and ending position of a given target value.

Your algorithm’s runtime complexity must be in the order of O(logn).

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

For example, Given [5, 7, 7, 8, 8, 10] and target value 8, return [3, 4].

二. 题目分析

题目大意是,给定一个已排序的序列和一个目标数字target,在这个序列中寻找等于target元素的下标范围。由于序列已经排好序,直接用二分查找,分别求等于target的最靠左的元素下标left和最靠右的元素下标right即可。

三. 示例代码

#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int n = nums.size();
        int left = searchRangeIndex(nums, target, 0, n - 1, true);
        int right = searchRangeIndex(nums, target, 0, n - 1, false);
        vector<int> result;
        result.push_back(left);
        result.push_back(right);
        return result;
    }

private:
    int searchRangeIndex(vector<int>& nums, int target, int low, int high, bool isLeft)
    {
        while (low <= high)
        {
            int midIndex = (low + high) >> 1;
            if (nums[midIndex] == target)
            {
                int temp = -1;
                if (isLeft)
                {
                    if (nums[midIndex] == nums[midIndex - 1] && low < midIndex)
                        temp = searchRangeIndex(nums, target, low, midIndex - 1, true);
                }
                else
                {
                    if (nums[midIndex] == nums[midIndex + 1] && high > midIndex)
                        temp = searchRangeIndex(nums, target, midIndex + 1, high, false);
                }
                return temp == -1 ? midIndex : temp; // temp == -1时表示只有中间一个值等于target
            }
            else if (nums[midIndex] > target)
                high = midIndex - 1;
            else
                low = midIndex + 1;
        }

        return -1; // 找不到target,输出-1

    }
};

这里写图片描述

四. 小结

注意题目要求O(logn)的时间复杂度,算法写的不好可能会超时。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值