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

思路:這道題是binary search的改進版。當尋找到target所在的k位置時,需要判斷target的起始索引值和終止索引值。可以這麼思考:首先得到k的位置,如果k不存在則返回[-1,-1];如果k存在,則起始的索引值肯定是在k的左半側,終止索引值在k的右半側。然後對這兩側再進行二分查找。因此總共的時間複雜度爲O(n)。
class Solution {
public:
    vector<int> searchRange(int A[], int n, int target) {
        vector<int> res;
        res.clear();
        if (n<=0) {
            res.push_back(-1);
            res.push_back(-1);
            return res;
        }
        int L = 0, R = n - 1, M;
        while(L <= R) {
            M = (L + R) / 2;
            if (A[M] > target) {
                R = M - 1;
            }
            else if(A[M] < target) {
                L = M + 1;
            }
            else {
                break;
            }
        }
        if (A[M] != target) {
            res.push_back(-1);
            res.push_back(-1);
        }
        else {
            L = 0, R = M - 1;
            int mid;
            while(R>=0 && A[R]==target) {
                mid = (L + R) / 2;
                if (A[mid] < target) {
                    L = mid + 1;
                }
                else if(A[mid] >= target) {
                    R = mid - 1;
                }
            }
            res.push_back(R + 1);
            L = M + 1,R = n - 1;
            while(L<n && A[L] == target) {
                mid = (L + R) / 2;
                if (A[mid] <= target) {
                    L = mid + 1;
                }
                else {
                    R = mid - 1;
                }
            }
            res.push_back(L-1);
        }
        return res;
    }
};


發佈了92 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章