【LeetCode】56.Merge Intervals(Medium)解题报告
2018-02-19 14:18
696 查看
【LeetCode】56.Merge Intervals(Medium)解题报告
题目地址:https://leetcode.com/problems/merge-intervals/description/
题目描述:
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].
非常重要,面试经常出现。扫描线算法这道题很经典的解法,前面meeting room的方法也可以用到这道题上。
Solution:
Date:2018年2月19日
题目地址:https://leetcode.com/problems/merge-intervals/description/
题目描述:
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].
非常重要,面试经常出现。扫描线算法这道题很经典的解法,前面meeting room的方法也可以用到这道题上。
Solution:
/** * 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; } * } */ //time:O(nlogn) //space:O(n) class Solution { public List<Interval> merge(List<Interval> intervals) { if(intervals == null || intervals.size() <=1) return intervals; //数据不是Array,list可以用Collections.sort()排序 Collections.sort(intervals,(a,b)->a.start - b.start); int start = intervals.get(0).start; int end = intervals.get(0).end; List<Interval> res = new ArrayList<>(); for(Interval interval : intervals){ if(interval.start <= end){ end = Math.max(end , interval.end); }else{ res.add(new Interval(start,end)); start = interval.start; end = interval.end; } } //把最后一个加进去 res.add(new Interval(start,end)); return res; } }
Date:2018年2月19日
相关文章推荐
- 【LeetCode】163.Missing Ranges(Medium)(带锁题)解题报告
- 【LeetCode】698.Partition to K Equal Sum Subsets(Medium)解题报告
- LeetCode解题报告 445. Add Two Numbers II [medium]
- LeetCode解题报告 55. Jump Game [medium]
- 【LeetCode】267.Palindrome Permutation II(Medium)解题报告
- LeetCode解题报告 279. Perfect Squares [medium]
- LeetCode解题报告 357. Count Numbers with Unique Digits [medium]
- 【LeetCode】419.Battleships in a Board(Medium)解题报告
- 【LeetCode】117.Populating Next Right Pointers in Each Node II(Medium)解题报告
- 【LeetCode】277.Find the Celebrity(Medium)解题报告(带锁题)
- 【LeetCode】245.Shortest Word Distance III(Medium)(加锁题)解题报告
- LeetCode解题报告 338. Counting Bits [medium]
- 【LeetCode】78.Subsets(Medium)解题报告
- 【LeetCode】376.Wiggle Subsequence(Medium)解题报告
- LeetCode解题报告 322. Coin Change [medium]
- LeetCode解题报告 241. Different Ways to Add Parentheses [medium]
- LeetCode解题报告 120. Triangle [medium]
- 【LeetCode】325.Maximum Size Subarray Sum Equals k(Medium)解题报告
- 【LeetCode】90.Subsets II(Medium)解题报告
- LeetCode解题报告 343. Integer Break [medium]