标签:book line efi you ota merge http log lis
56. Merge Intervals https://www.youtube.com/watch?v=6tLHjei-f0I 这个就是 sweep line Time nlogn sorting and o(n) for merge So nlogn in total Space o(n) if no overlapping intervals https://github.com/tongzhang1994/Facebook-Interview-Coding/blob/master/56.%20Merge%20Intervals.java 注意:1.别忘先sort 2.中间用if-else 3.loop后别忘add最后一个interval // sort the intervals by starting time first // take the first interval , and compare with the second // interval // and check if the second interval starts before the // first interval ends, if yes, take the max of their end as the end // of the first interval. //if no overlap, then add the first interval into the // result, and move onto the second interval inorder to compare with the rest /** * 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; } * } */ class Solution { public List<Interval> merge(List<Interval> intervals) { if(intervals.size() <= 1){ return intervals; } // Collections.sort(), not Arrays.sort() Collections.sort(intervals, new Comparator<Interval>(){ @Override public int compare(Interval i1, Interval i2){ if(i1.start < i2.start){ return -1; }else if( i1.start > i2.start){ return 1; }else{ return 0; } }); int start = intervals.get(0).start; int end = intervals.get(0).end; List<Interval> result = new ArrayList<>(); for(Interval interval : intervals){ if(interval.start <= end){ end = Math.max(interval.end, end); }else{ result.add(new Interval(start, end)); start = interval.start; end = interval.end; } } result.add(new Interval(start, end)); return result; } }
标签:book line efi you ota merge http log lis
原文地址:https://www.cnblogs.com/tobeabetterpig/p/9454889.html