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.html
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.git
Note:github
Example 1:數組
Input: [ [1,2] ] Output: [-1] Explanation: There is only one interval in the collection, so it outputs -1.
Example 2:app
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,咱們在 HashMap 中找到該區間的座標加入結果 res 中便可,參見代碼以下:post
解法一:ui
class Solution { public: vector<int> findRightInterval(vector<vector<int>>& intervals) { vector<int> res, starts; unordered_map<int, int> m; for (int i = 0; i < intervals.size(); ++i) { m[intervals[i][0]] = i; starts.push_back(intervals[i][0]); } sort(starts.rbegin(), starts.rend()); for (auto interval : intervals) { int i = 0; for (; i < starts.size(); ++i) { if (starts[i] < interval[1]) break; } res.push_back((i > 0) ? m[starts[i - 1]] : -1); } return res; } };
上面的解法能夠進一步化簡,咱們能夠利用 STL 的 lower_bound 函數來找第一個不小於目標值的位置,這樣也能夠達到咱們的目標,參見代碼以下:url
解法二:spa
class Solution { public: vector<int> findRightInterval(vector<vector<int>>& intervals) { vector<int> res; map<int, int> m; for (int i = 0; i < intervals.size(); ++i) { m[intervals[i][0]] = i; } for (auto interval : intervals) { auto it = m.lower_bound(interval[1]); if (it == m.end()) res.push_back(-1); else res.push_back(it->second); } return res; } };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/436
相似題目:
Data Stream as Disjoint Intervals
參考資料:
https://leetcode.com/problems/find-right-interval/
https://leetcode.com/problems/find-right-interval/discuss/91819/C%2B%2B-map-solution