【leetcode】34. Search for a Range 給定陣列的給定值的下標範圍

knzeus發表於2019-05-10

1. 題目

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(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].

2. 思路

基於二分搜尋進行。分別查詢最低位和最高位。
找最低位是,每次找到了之後,不是立刻退出,而是繼續在左側進一步查詢,直到再也找不到的時候,返回上一次找到的位置。
找最高位類似。

3. 程式碼

耗時:9ms

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> ret;
        int i = bsearch_low(nums, 0, nums.size(), target);
        ret.push_back(i);
        if (i == -1) {
            ret.push_back(-1);
            return ret;
        }
        int j = bsearch_high(nums, 0, nums.size(), target);
        ret.push_back(j);
        return ret;
    }
    
    int bsearch(vector<int>& nums, int i, int j, int target) {
        if (i >= j) { return -1; }
        if (i+1 == j) { return nums[i] == target ? i : -1; }
        int k = i + (j - i) / 2;
        if (nums[k] == target) {
            return k;
        } else if (nums[k] < target) {
            return bsearch(nums, k+1, j, target);
        } else {
            return bsearch(nums, i, k, target);
        }
    }
    
    int bsearch_low(vector<int>& nums, int i, int j, int target) {
        int k = -1;
        while (true) {
            int n = bsearch(nums, i, j, target);
            if (n == -1) {
                return k;
            } else {
                j = n;
                k = n;
            }
        }
    }
    
    int bsearch_high(vector<int>& nums, int i, int j, int target) {
        int k = -1;
        while (true) {
            int n = bsearch(nums, i, j, target);
            if (n == -1) {
                return k;
            } else {
                i = n + 1;
                k = n;
            }
        }
    }
};

相關文章