美文网首页
Find First and Last Position of

Find First and Last Position of

作者: ticks | 来源:发表于2019-06-24 15:31 被阅读0次

    在升序数组中找到 target 的范围

    要求O(\log n)

    自然想到二分查找

    1. 查找下限
      nums[mid]<target left=mid;
      else right=mid;
    2. 查找上限
      nums[mid]>target right = mid
      else left = mid
    class Solution
    {
    public:
        vector<int> searchRange(vector<int>& nums, int target)
        {
            vector<int> res(2, -1);
            int size = nums.size();
            if (size == 0) return res;
            int left = 0, right = size - 1;
            while (right > left)
            {
                int mid = (left + right) / 2;
                if (nums[mid] < target)
                    left = mid + 1;
                else
                    right = mid;
            }
            if (nums[left] == target)
                res[0] = left;
            else
                return res;
            left = 0;
            right = size - 1;
            while (left < right)
            {
                int mid = (left + right + 1) / 2;
                if (nums[mid] > target)
                    right = mid - 1;
                else
                    left = mid;
            }
            res[1] = right;
            return res;
        }
    };
    

    ✔ Accepted
    ✔ 88/88 cases passed (8 ms)
    ✔ Your runtime beats 92.89 % of cpp submissions
    ✔ Your memory usage beats 76.77 % of cpp submissions (10.3 MB)

    相关文章

      网友评论

          本文标题:Find First and Last Position of

          本文链接:https://www.haomeiwen.com/subject/rqcoqctx.html