1. 程式人生 > >[LeetCode] Search for a Range

[LeetCode] Search for a Range

ted runt found vector class arch algorithm com pty

Given an array of integers 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].

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

.

使用兩次二分查找,第一次找出目標數的左邊界,第二次找出目標數的右邊界。最後判斷邊界並返回。

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        if (nums.empty())
            return {-1, -1};
        int lower = -1, upper = -1, mid = 0;
        
        int left = 0, right = nums.size() - 1
; while (left <= right) { mid = (left + right) / 2; if (nums[mid] < target) left = mid + 1; else right = mid - 1; } lower = left; left = 0, right = nums.size() - 1; while (left <= right) { mid
= (left + right) / 2; if (nums[mid] > target) right = mid - 1; else left = mid + 1; } upper = right; if (lower > upper) return {-1, -1}; else return {lower, upper}; } }; // 16 ms

[LeetCode] Search for a Range