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

lintcode-easy-Insert Interval

时间:2016-02-25 15:09:58      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:

Given a non-overlapping interval list which is sorted by start point.

Insert a new interval into it, make sure the list is still in order and non-overlapping (merge intervals if necessary).

 

Example

Insert [2, 5] into [[1,2], [5,9]], we get [[1,9]].

Insert [3, 4] into [[1,2], [5,9]], we get [[1,2], [3,4], [5,9]].

 

这题记得第一次刷的时候花了挺长时间做出来的,看了下九章算法上贴的答案,觉得还是那个答案写的好,如下

/**
 * Definition of Interval:
 * public classs Interval {
 *     int start, end;
 *     Interval(int start, int end) {
 *         this.start = start;
 *         this.end = end;
 *     }
 */

class Solution {
    /**
     * Insert newInterval into intervals.
     * @param intervals: Sorted interval list.
     * @param newInterval: A new interval.
     * @return: A new sorted interval list.
     */
    public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) {
        ArrayList<Interval> result = new ArrayList<Interval>();
        // write your code here
        
        if(intervals == null || newInterval == null)
            return null;
        
        int insertPosition = 0;
        
        for(Interval interval: intervals){
            if(newInterval.start > interval.end){
                result.add(interval);
                insertPosition++;
            }
            else if(newInterval.end < interval.start){
                result.add(interval);
            }
            else{
                newInterval.start = Math.min(newInterval.start, interval.start);
                newInterval.end= Math.max(newInterval.end, interval.end);
            }
        }
        
        result.add(insertPosition, newInterval);
        
        return result;
    }
}

 

lintcode-easy-Insert Interval

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5216765.html

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