【leetcode】搜索範圍(二分查找升序數組target元素上下界)

34. Search for a Range

leetcode題目描述

題目描述:

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

題解:

在升序數組中找到target的初始位置和終止位置。
二分查找實現lower_bound和upper_bound
1. auto被解釋爲一個自動存儲變量的關鍵字,也就是申明一塊臨時的變量內存
2. distance(it1,it2)取到兩迭代器間距離
3. next(it,n) 指向從it開始(本身不計)的第n個元素的迭代器
4. prev(it)得到it遞減後的值
5. 注意求上界時,判斷條件value >= *mid,第一次找到target值後仍向後半部分找

solution1


class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        auto lower = lower_bound(nums.begin(), nums.end(), target);
        auto upper = upper_bound(lower, nums.end(), target);
        if (lower == nums.end() || *lower != target) {
            // 未找到target
            return vector<int>{-1,-1}; 
        } else {
            return vector<int>{distance(nums.begin(), lower),distance(nums.begin(),prev(upper))};
        }
    }

    template<typename ForwardIterator, typename T>
    ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last, T value) {
        while (first != last) {
        /*  其中auto和register對應自動存儲期。
            具有自動存儲期的變量在進入聲明該變量的程序塊時被建立,
            它在該程序塊活動時存在,退出該程序塊時撤銷。
            在函數內部定義的變量成爲局部變量。
        */
        /*distance取到兩迭代器間距離
          next(it,n) 指向從it開始(本身不計)的第n個元素的迭代器*/
            auto mid = next(first, distance(first,last)/2);
            if (value > *mid) {
                first = ++mid;
            } else {
                last = mid;
            }
        }
        return first;
    }

    template<typename ForwardIterator, typename T>
    ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last, T value) {
        while (first != last) {
            auto mid = next(first, distance(first,last)/2);
            if (value >= *mid) {
                first = ++mid; // 找到一次後仍向後半部分找,最後first停在上界+1 
            } else {
                last = mid;
            } 
        }
        return first;
    }

};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章