zoukankan      html  css  js  c++  java
  • 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 };

     

  • 相关阅读:
    Android中的“再按一次返回键退出程序”代码实现
    Android UI编程之自定义控件初步——ImageButton
    21岁,我想当“大帅”
    茑萝改变了我
    茑萝,梦想的加油站
    放弃了我的国企工作
    性能调优之访问日志IO性能优化
    性能调优之提高 ASP.NET Web 应用性能的 24 种方法和技巧
    性能调优之剖析OutOfMemoryError
    老李分享:单元测试检查清单:让测试有效,避免致命错误
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/13503126.html
Copyright © 2011-2022 走看看