LeetCode: Merge Intervals 解题报告
2014-10-26 20:45
369 查看
[b]
View Code
[b]GITHUB CODE
REF: /article/1346945.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 List<Interval> merge(List<Interval> intervals) { List<Interval> ret = new ArrayList<Interval>(); if (intervals == null || intervals.size() == 0) { return ret; } Collections.sort(intervals, new Comparator<Interval>() { public int compare(Interval o1, Interval o2) { // sort the intervals by the start. return o1.start - o2.start; } }); // 作为最后一个插入的区间 Interval last = intervals.get(0); // 这里要考虑性能。使用iterator的话,对linkedlist会更快. Iterator<Interval> itor = intervals.iterator(); while (itor.hasNext()) { Interval cur = itor.next(); // cur 在last的右边 if (cur.start > last.end) { // 将cur作为新的last. ret.add(last); last = cur; // cur与last有重合的部分,合并之 } else { int s = last.start; int e = Math.max(last.end, cur.end); last = new Interval(s, e); } } // 把最后一个区间加上 ret.add(last); return ret; } }
View Code
[b]GITHUB CODE
REF: /article/1346945.html
相关文章推荐
- [LeetCode]Merge Intervals, 解题报告
- 【LeetCode】Merge Intervals 解题报告
- 【LeetCode】Merge Intervals 解题报告
- [leetcode] 286. Walls and Gates 解题报告
- Leetcode 409. Longest Palindrome 构造最长回文串 解题报告
- [Leetcode] 55. Jump Game 解题报告
- 【LeetCode】Longest Palindromic Substring 解题报告
- [Leetcode] 271. Encode and Decode Strings 解题报告
- [Leetcode] 58. Length of Last Word 解题报告
- 【LeetCode】521. Longest Uncommon Subsequence I 解题报告(Python)
- [leetcode] 165. Compare Version Numbers 解题报告
- 【LeetCode】733. Flood Fill 解题报告(Python)
- 【LeetCode】11. Container With Most Water 解题报告
- [LeetCode 解题报告]001.Two Sum
- LeetCode解题报告--Container With Most Water
- [LeetCode] Maximum Subarray 解题报告
- [Leetcode] 363. Max Sum of Rectangle No Larger Than K 解题报告
- Leetcode 119. Pascal's Triangle II 杨辉三角2 解题报告
- 【LeetCode】Reverse Words in a String III 解题报告
- 【LeetCode】3Sum Closest 解题报告