zoukankan      html  css  js  c++  java
  • 057 Insert Interval 插入区间

    给出一个无重叠的按照区间起始端点排序的区间列表。
    在列表中插入一个新的区间,你要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。
    示例 1:
    给定区间 [1,3],[6,9],插入并合并 [2,5] 得到 [1,5],[6,9].
    示例 2:
    给定区间 [1,2],[3,5],[6,7],[8,10],[12,16],插入并合并 [4,9] 得到 [1,2],[3,10],[12,16].
    这是因为新的区间 [4,9] 与 [3,5],[6,7],[8,10] 重叠。
    详见:https://leetcode.com/problems/insert-interval/description/

    Java实现:

    /**
     * Definition for an interval.
     * public class Interval {
     *     int start;
     *     int end;
     *     Interval() { start = 0; end = 0; }
     *     Interval(int s, int e) { start = s; end = e; }
     * }
     */
    class Solution {
        public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
            List<Interval> res = new ArrayList<Interval>();
                
            for(Interval each: intervals){
                if(each.end < newInterval.start){
                    res.add(each);
                }else if(each.start > newInterval.end){
                    res.add(newInterval);
                    newInterval = each;        
                }else if(each.end >= newInterval.start || each.start <= newInterval.end){
                    int nstart = Math.min(each.start, newInterval.start);
                    int nend = Math.max(newInterval.end, each.end);
                    newInterval = new Interval(nstart, nend);
                }
            }
            res.add(newInterval); 
            return res;
        }
    }
    

    参考:https://www.cnblogs.com/springfor/p/3872333.html

  • 相关阅读:
    Socket与系统调用深度分析
    需求分析:未来的图书会是怎么样的?
    构建调试Linux内核网络代码的环境MenuOS系统
    jmeter--开始
    pytest---api
    pytest---mark
    pytest---数据处理
    pytest---fixture运行规则
    pytest---allure(mac版本)
    pytest---pytest.ini
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8698614.html
Copyright © 2011-2022 走看看