LeetCode 34 Search for a Range

題意:

給出有序序列,查找target在序列中出現的下標區間。


思路:

熟練使用C++的upper_bound和lower_bound……


代碼:

class Solution {
public:
    vector<int> searchRange(vector<int> &nums, int target) {
        int l = lower_bound(nums.begin(), nums.end(), target) - nums.begin();
        if (l == nums.size() || nums[l] != target) {
            return vector<int> {-1, -1};
        }
        int r = upper_bound(nums.begin(), nums.end(), target) - nums.begin();
        return vector<int> {l, r - 1};
    }
};


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