leetCode 57.Insert Interval (插入区间) 解题思路和方法

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].


思路:插入合并就可以,相比于上一题。这题还要简单一些。

详细代码例如以下:

/**
 * 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; }
 * }
 */
public class Solution {
    public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
    	 List<Interval> list = new ArrayList<Interval>();
    	//边界情况
        if(intervals.size() == 0){
        	list.add(newInterval);
        	return list;
        }
        //循环推断
        for(int i = 0; i < intervals.size();i++){
        	//假设新的区间结束值小于開始值。则直接插入前面。后面依次插入就可以
        	if(newInterval.end < intervals.get(i).start){
        		list.add(newInterval);
        		for(int j = i; j < intervals.size(); j++){
        			list.add(intervals.get(j));
        		}
        		break;
        	}
        	//新的区间開始点大于结束点。则当前点直接加入结果集
        	else if(newInterval.start > intervals.get(i).end){
                list.add(intervals.get(i));
            }
        	//须要合并的情况
        	else{
        		//合并区间
                newInterval.start = Math.min(newInterval.start,intervals.get(i).start);
                newInterval.end = Math.max(newInterval.end,intervals.get(i).end);
            }
            if(i == intervals.size() - 1){//假设是最后一个数据。也加入结果集中
                list.add(newInterval);
            }
        }
        return list;
    }
}


posted on 2017-07-29 19:25  blfbuaa  阅读(251)  评论(0编辑  收藏  举报