LeetCode——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.

解法

先将其按start的大小从小到大排序,再遍历,如果当前interval的start小于或等于res里面最后一个interval的end,则把他们两个合并,如果大于则将当前interval添加到res中

public List<Interval> merge(List<Interval> intervals) {
		List<Interval> res=new ArrayList<Interval>();
		if(intervals==null||intervals.size()==0)
			return res;
		intervals.sort(new Comparator<Interval>() {

			@Override
			public int compare(Interval o1, Interval o2) {
				// TODO Auto-generated method stub
				return o1.start-o2.start;
			}
			
		});
		int n=intervals.size();
		Interval I=intervals.get(0);
		res.add(intervals.get(0));
		for(int i=1;i<n;i++)
		{
			if(res.get(res.size()-1).end>=intervals.get(i).start)
				res.get(res.size()-1).end=Math.max(intervals.get(i).end,res.get(res.size()-1).end);
			else
				res.add(intervals.get(i));			
		}
		return res;
    }

Runtime: 12 ms, faster than 84.87% of Java online submissions for Merge Intervals.
Memory Usage: 46 MB, less than 5.76% of Java online submissions for Merge Intervals.

解法二

把start和end分别保存在数组中再从小到大排序,然后遍历数组,如果starts[i+1]>ends[i]则说明不连续了,要把之前的加入数组当中

public List<Interval> merge(List<Interval> intervals) {
		List<Interval> res=new ArrayList<Interval>();
		if(intervals==null||intervals.size()==0)
			return res;
		int n=intervals.size();
		int[] starts=new int[n];
		int[] ends=new int[n];
		int i=0;
		for(Interval I:intervals)
		{
			starts[i]=I.start;
			ends[i++]=I.end;
		}
        Arrays.sort(starts);
        Arrays.sort(ends);
		int j=0;
		for(i=0;i<n;i++)
		{
			if(i==n-1||starts[i+1]>ends[i])
			{
				res.add(new Interval(starts[j],ends[i]));
				j=i+1;
			}
		}
		return res;
	}

Runtime: 7 ms, faster than 99.68% of Java online submissions for Merge Intervals.
Memory Usage: 44.8 MB, less than 38.20% of Java online submissions for Merge Intervals.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值