zoukankan      html  css  js  c++  java
  • [LeetCode]-- Merge Intervals

     

    Given a collection of intervals, merge all overlapping intervals.

    For example,
    Given [1,3],[2,6],[8,10],[15,18],
    return [1,6],[8,10],[15,18].

    遍历list,将每个interval插入到result中去

    insert interval :  http://www.cnblogs.com/RazerLu/p/3532267.html

    /**
     * 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> merge(ArrayList<Interval> intervals) {
            ArrayList<Interval> result = new ArrayList<Interval>();
            
            for(int i =0; i < intervals.size(); i++){
                Interval temp = intervals.get(i);
                result = insert(result, temp);
            }
             return result;
        }
        
        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;
        }
    }
  • 相关阅读:
    我觉得 一个 单片机 代码 程序猿 连一个链表都不会写的 话 ,太说不过去了 ,学习 一下
    peripheralStateNotificationCB
    SimpleProfile_GetParameter && SimpleProfile_SetParameter
    performPeriodicTask
    如何在IAR工程中创建和使用模板
    英语 单词 收集
    KD-树(下)
    KD-树(上)
    KNN
    命令方式联网与界面network-manager方式联网
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3532274.html
Copyright © 2011-2022 走看看