1. 程式人生 > >leetCode 57.Insert Interval (插入區間) 解題思路和方法

leetCode 57.Insert Interval (插入區間) 解題思路和方法

use example ava article urn win time 例如 ont

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 (插入區間) 解題思路和方法