1. 程式人生 > >[LeetCode] Find Right Interval 找右區間

[LeetCode] Find Right Interval 找右區間

Given a set of intervals, for each of the interval i, check if there exists an interval j whose start point is bigger than or equal to the end point of the interval i, which can be called that j is on the "right" of i.

For any interval i, you need to store the minimum interval j's index, which means that the interval j has the minimum start point to build the "right" relationship for interval i. If the interval j doesn't exist, store -1 for the interval i. Finally, you need output the stored value of each interval as an array.

Note:

  1. You may assume the interval's end point is always bigger than its start point.
  2. You may assume none of these intervals have the same start point.

Example 1:

Input: [ [1,2] ]

Output: [-1]

Explanation: There is only one interval in the collection, so it outputs -1.

Example 2:

Input: [ [3,4], [2,3], [1,2] ]

Output: [-1, 0, 1]

Explanation: There is no satisfied "right" interval for [3,4].
For [2,3], the interval [3,4] has minimum-"right" start point;
For [1,2], the interval [2,3] has minimum-"right" start point.

Example 3:

Input: [ [1,4], [2,3], [3,4] ]

Output: [-1, 2, -1]

Explanation: There is no satisfied "right" interval for [1,4] and [3,4].
For [2,3], the interval [3,4] has minimum-"right" start point.

這道題給了我們一堆區間,讓我們找每個區間的最近右區間,要保證右區間的start要大於等於當前區間的end,由於區間的順序不能變,所以我們不能給區間排序,我們需要建立區間的start和該區間位置之間的對映,由於題目中限定了每個區間的start都不同,所以不用擔心一對多的情況出現。然後我們把所有的區間的start都放到一個數組中,並對這個陣列進行降序排序,那麼start值大的就在陣列前面。然後我們遍歷區間集合,對於每個區間,我們在陣列中找第一個小於當前區間的end值的位置,如果陣列中第一個數就小於當前區間的end,那麼說明該區間不存在右區間,結果res中加入-1;如果找到了第一個小於當前區間end的位置,那麼往前推一個就是第一個大於等於當前區間end的start,我們在雜湊表中找到該區間的座標加入結果res中即可,參見程式碼如下:

解法一:

class Solution {
public:
    vector<int> findRightInterval(vector<Interval>& intervals) {
        vector<int> res, v;
        unordered_map<int, int> m;
        for (int i = 0; i < intervals.size(); ++i) {
            m[intervals[i].start] = i;
            v.push_back(intervals[i].start);
        }
        sort(v.begin(), v.end(), greater<int>());
        for (auto a : intervals) {
            int i = 0;
            for (; i < v.size(); ++i) {
                if (v[i] < a.end) break;
            }
            res.push_back((i > 0) ? m[v[i - 1]] : -1);
        }
        return res;
    }
};

上面的解法可以進一步化簡,我們可以利用STL的lower_bound函式來找第一個不小於目標值的位置,這樣也可以達到我們的目標,參見程式碼如下:

解法二:

class Solution {
public:
    vector<int> findRightInterval(vector<Interval>& intervals) {
        vector<int> res;
        map<int, int> m;
        for (int i = 0; i < intervals.size(); ++i) {
            m[intervals[i].start] = i;
        }
        for (auto a : intervals) {
            auto it = m.lower_bound(a.end);
            if (it == m.end()) res.push_back(-1);
            else res.push_back(it->second);
        }
        return res;
    }
};

類似題目:

參考資料: