码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-07-15 15:08:53      阅读:1089      评论:0      收藏:0      [点我收藏+]

标签: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].


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

具体代码如下:

/**
 * 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;
    }
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

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

标签:leetcode   合并   

原文地址:http://blog.csdn.net/xygy8860/article/details/46892533

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!