二分

【leetcode】34. Find First and Las

2019-05-05  本文已影响0人  邓泽军_3679

1、题目描述

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]

2、问题描述:

3、问题关键:

4、C++代码:

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        if (nums.empty()) return vector<int>({-1, -1});
        int n = nums.size();
        vector<int> res;
        int l = 0, r = n - 1;
        while(l < r) {
            int mid = l + r >> 1;//小于等于k的最大值。(答案在左边)
            if (nums[mid] >= target) r = mid;
            else l = mid + 1;
        }
        if (nums[l] != target) return vector<int>({-1, -1});//不存在这个数。
        res.push_back(l);
        l = 0, r = n - 1;
        while(l < r) {
            int mid = l + r + 1 >> 1;//大于等于target的最小值。(答案在右边)
            if (nums[mid] <= target) l = mid;
            else r = mid - 1;
        }
        res.push_back(l);
        return res;
    }
};
上一篇下一篇

猜你喜欢

热点阅读