Java Merge Intervals(合并间隔)

Problem:

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

Thoughts of This Problem

The key to solve this problem is defining a Comparator first to sort the arraylist of Intevals. And then merge some intervals.

The take-away message from this problem is utilizing the advantage of sorted list/array.

Java Solution

package com.soszou.java.leetcode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class MergeIntervals {
	public static void main(String[] args) {
		//[1,3],[2,6],[8,10],[15,18],
		Interval a = new Interval(1, 3);
		Interval c = new Interval(2, 6);
		Interval b = new Interval(8, 10);
		Interval d = new Interval(15, 18);
		ArrayList intervals = new ArrayList();
		intervals.add(a);
		intervals.add(b);
		intervals.add(c);
		intervals.add(d);
		
		merge(intervals);
	}
	
	public static ArrayList merge(ArrayList intervals) {

		if (intervals == null || intervals.size() <= 1)
			return intervals;

		// sort intervals by using self-defined Comparator
		Collections.sort(intervals, new IntervalComparator());

		ArrayList result = new ArrayList();

		Interval prev = intervals.get(0);
		for (int i = 1; i < intervals.size(); i++) {
			Interval curr = intervals.get(i);

			if (prev.end >= curr.start) {
				// merged case
				Interval merged = new Interval(prev.start, Math.max(prev.end,
						curr.end));
				prev = merged;
			} else {
				result.add(prev);
				prev = curr;
			}
		}

		result.add(prev);
		for (int i = 0; i < result.size(); i++) {
			Interval interval =result.get(i);
			System.out.println("[ "+interval.start+"-"+interval.end+" ]");
		}
		return result;
	}
}

class IntervalComparator implements Comparator {
	public int compare(Interval i1, Interval i2) {
		return i1.start - i2.start;
	}
}


转载自:http://www.programcreek.com/2012/12/leetcode-merge-intervals/

你可能感兴趣的:(Java,算法)