[LeetCode]--Insert Intervals

[LeetCode]--Insert Intervals
/**
 * 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 ArrayList<Interval> insert(ArrayList<Interval> intervals,
            Interval newInterval) {
                
        ArrayList<Interval> result = new ArrayList<Interval>();
        
        for(int i = 0; i < intervals.size(); i ++){
            Interval temp = intervals.get(i);
            
            if(temp.start> newInterval.end){
                result.add(newInterval);
                for(int j = i; j < intervals.size(); j++){
                    result.add(intervals.get(j));
                }
                return result;
            } else if( newInterval.start > temp.end){
                result.add(temp);
                continue;
            } else{
                // Attention : method Math.min and Math.max
                newInterval.start = Math.min(newInterval.start, temp.start);
                newInterval.end = Math.max(newInterval.end, temp.end);
            }
        }
        /*easy to forget. The situation that newInterval.start is the biggest */
        result.add(newInterval);
        return result;
    }
}
[LeetCode]--Insert Intervals

[LeetCode]--Insert Intervals

上一篇:(4)构建和安装-Firefox OS 构建概览


下一篇:[LeetCode]--Set Matrix Zeros