Leetcode 56. 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].

  • Total Accepted: 113975
  • Total Submissions: 391534
  • Difficulty: Medium
  • Contributor: LeetCode

思路:

题目要求要进行二元数组的合并,思路如下:

1. 先进行排序,复写比较器的方法,按照Interval的start数值进行排序,这样,整个list就是按照start从小到大的顺序进行排列的

2. 将intervals的第一个数添加进结果集里

3. 然后针对intervals从1开始,挨个比较,每次比较时将结果集的最后一个元素(current)与intervals 的当前元素(now)比较,如果,now的start都比current的end大,那么这个元素可以插进res集里

如果没有,那么比较now的end和current的end,谁的大,就把current的end替换成它

4. 返回结果集res

代码:

/**
 * 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) {
        if(intervals.size() <= 0) return intervals;
        Collections.sort(intervals, new Comparator<Interval>() {
			@Override
			public int compare(Interval o1, Interval o2) {
				return o1.start - o2.start;
			}
		});
        List<Interval> res = new ArrayList();
        res.add(intervals.get(0));
        for(int i = 1; i < intervals.size(); ++i) {
        	Interval current = res.get(res.size()-1);
        	Interval now = intervals.get(i);
        	if(now.start > current.end) res.add(now);
        	else {
        		int max = Math.max(current.end, now.end);
        		current.end = max;
        	}
        }
        return res;
    }
}


posted on 2017-03-30 14:29  lantx  阅读(123)  评论(0编辑  收藏  举报