LC436. Find Right Interval

分析:求一个区间最邻近的右边的区间在数组中的索引位置,右侧区间头要大于等于左侧区间尾。用map存区间头对应的区间索引。

标准库有map自己的lower_bound函数,返回大于等于key的第一个值的iteraotr。找右侧最邻近区间就是找 lower_bound(intervals[i][1]) .

class Solution {
public:
    vector<int> findRightInterval(vector<vector<int>>& intervals) {
        map<int, int> hash;
        vector<int> res;
        int n = intervals.size();
        for (int i = 0; i < n; ++i) {
            hash[intervals[i][0]] = i;
        }
        for (auto& in : intervals) {
            auto it = hash.lower_bound(in[1]);
            if (it == hash.end()) res.push_back(-1);
            else res.push_back(it->second);
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/betaa/p/12529928.html