【LeetCode】[56] Merge Intervals

Given a collection of intervals, merge all overlapping intervals.

Example 1:

Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].

Example 2:

Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.

NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

以前做过区间合并的笔试题,竟然忘了解题方法,记录一下。

区间合并提供了两个思路,第一个就是开一个很大的数组,将区间依次遍历,遍历的整数设为true。这种方法适用于数字范围小,时间复杂度要求高的情况,且不具有普遍适用性。

第二种方法比较正常,就是根据区间第一个数进行排序, 然后依次遍历合并区间。在区间合并方法中,使用的C原因,这次我用的JAVA又写了一遍。

package mergerIntervals;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import test1.Interval;

/*
 * 项目名称: 合并区间
 * 描述: 给出若干个区间,合并相互重叠的区间
 * 创建时间: 2019-4-30
 * @author: cys
 * @version v1.0
 */
class Interval implements Comparable { //实现Comparable排序接口,
	int start;
	int end;
	public Interval(int start, int end){
		this.start = start;
		this.end = end;
	}
	public int compareTo(Interval interval){
		if(this.start-interval.start != 0){
			return this.start-interval.start;
		}else{
			return this.end - interval.end;
		}
	}
}
public class Main {
	 private static boolean overlap(Interval a, Interval b) {  //返回两个区间是否存在覆盖情况
	        return a.start <= b.end && b.start <= a.end;
	    }
	

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[][] intervals = {{1,3},{3,6},{5,9},{11,14},{12,13}};
	
		Interval inters[] = new Interval[intervals.length];
		
        for(int i=0;i intervals2 = new ArrayList<>();
				
		if(intervals.length!=0){
			Interval interval = new Interval(inters[0].start, inters[0].end);
			
			intervals2.add(interval);
		}
		for(int i=1;i

 

你可能感兴趣的:(Leetcode)