zoukankan      html  css  js  c++  java
  • leetcode--Insert Interval

    Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

    You may assume that the intervals were initially sorted according to their start times.

    Example 1:
    Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].

    Example 2:
    Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].

    This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].

    public class Solution {
        public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
            List<Interval> result = new ArrayList<Interval>();
    		if(!intervals.isEmpty()){
    			int size = intervals.size();
    			int i = 0;
    			while(i < size && intervals.get(i).start < newInterval.start){
    				++i;
    			}
    			intervals.add(i, newInterval);
    			int start = intervals.get(0).start, end = intervals.get(0).end;
    			for(int j = 1; j < size + 1; ++j){
    				Interval anInterval = intervals.get(j);
    				if(anInterval.start <= end){
    					end = Math.max(end, anInterval.end);
    				}
    				else{
    					result.add(new Interval(start, end));
    					start = anInterval.start;
    					end = anInterval.end;
    				}
    			}
    			result.add(new Interval(start, end));
    		}
    		else
    			result.add(newInterval);
    		return result;    
        }
    }
    

      

  • 相关阅读:
    Shell脚本编程基础之程序
    从入门到放弃
    Shell编写的俄罗斯方块游戏(亲测可用)
    Qt开发环境搭建
    day01
    day01
    浅析STM32内部FLASH读写
    基于STM32 的485通讯实验(f103)
    八、Servlet的常见错误总结:
    七、Servlet介绍
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3787566.html
Copyright © 2011-2022 走看看