436. Find Right Interval

问题:

给定一组间隔列表,每个间隔有[left, right]两个值组成。

对于每一个间隔,求是否有另一个间隔在它的右边:另一个间隔的left>=这个间隔的right

若存在,将满足的index最小的另一个间隔的index存入结果。

否则将 -1 存入结果。

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.

NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

  

解法:hash + 二分查找(Binary Search)

这里用到map的lower_bound方法:对key进行查找。

首先利用hash的map保存:posleft

  • key:[每个间隔的left]
  • value:[每个间隔的index]

这样,在遍历构建map的同时,已经获得以key升序排列的map

然后,再遍历原先间隔数组,

对每一个间隔的right,

在 posleft 中,找到最小的key>=right的对象,取得其value,存入res

若未找到,即lower_bound方法返回iterator指针指向map的end。将 -1 存入res。

 

代码参考:

 1 class Solution {
 2 public:
 3     vector<int> findRightInterval(vector<vector<int>>& intervals) {
 4         map<int, int> posleft;//<left, index>
 5         vector<int> res;
 6         int i=0;
 7         for(vector<int> itv:intervals) {
 8             posleft[itv[0]]=i;
 9             i++;
10         }
11         for(vector<int> itv:intervals) {
12             auto pos = posleft.lower_bound(itv[1]);//find left by this.right
13             if(pos!=posleft.end()) res.push_back(pos->second);
14             else res.push_back(-1);
15         }
16         return res;
17     }
18 };

 

 

posted @ 2020-08-14 16:51  habibah_chang  阅读(104)  评论(0编辑  收藏  举报