[LeetCode35]Insert Intervals

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

Analysis:

In other words, the questions gives a new interval, the task is to insert this new interval into an ordered non-overlapping intervals. Consider the merge case.

Idea to solve this problem is quite straight forward:
1. Insert the new interval according to the start value.
2. Scan the whole intervals, merge two intervals if necessary.

Can use code from previous question

Java

public class Solution {
    class IntervalCompartor implements Comparator<Interval>{
		@Override
		public int compare(Interval o1, Interval o2) {
			// TODO Auto-generated method stub
			return o1.start-o2.start;
		}
	}
	public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
        List<Interval> result = new ArrayList<>();
        if(intervals.size()<=0){
        	result.add(newInterval);
        	return result;
        }
        int i=0;
        for(;i<intervals.size();i++){
        	if(newInterval.start<intervals.get(i).start){
        		intervals.add(i, newInterval);
        		break;
        	}
        }
        if(i==intervals.size()) intervals.add(newInterval);
        Collections.sort(intervals, new IntervalCompartor());
        result.add(intervals.get(0));
        for(i=1;i<intervals.size();i++){
        	Interval tem = result.get(result.size()-1);
        	if(tem.end>=intervals.get(i).start){
        		tem.end = Math.max(tem.end, intervals.get(i).end);
        		result.set(result.size()-1, tem);
        	}else {
				result.add(intervals.get(i));
			}
        }
        return result;
    }
}
c++

class Solution {
public:
    vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
        vector<Interval> result;
    vector<Interval>::iterator it;
    for(it = intervals.begin();it!=intervals.end();it++){
        if(newInterval.start<(*it).start){
            intervals.insert(it,newInterval);
            break;
        }
    }
    if(it == intervals.end())
        intervals.insert(it,newInterval);
    if(intervals.empty()) return result;
    result.push_back(*intervals.begin());
    for(it = intervals.begin()+1; it!=intervals.end();it++){
        if(result.back().end>=(*it).start){
            result.back().end = max(result.back().end,(*it).end);
        }else{
            result.push_back(*it);
        }
    }
    return result;
    }
};



你可能感兴趣的:(LeetCode,comparator)