435. Non-overlapping Intervals && 436. Find Right Interval && 452. Minimum Number of Arrows to Burst

 

Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.

Note:

  1. You may assume the interval's end point is always bigger than its start point.
  2. Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other.

 

Example 1:

Input: [ [1,2], [2,3], [3,4], [1,3] ]

Output: 1

Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.

 

Example 2:

Input: [ [1,2], [1,2], [1,2] ]

Output: 2

Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.

 

Example 3:

Input: [ [1,2], [2,3] ]

Output: 0

Explanation: You don't need to remove any of the intervals since they're already non-overlapping.

 

思路:对于这种Interval的一般都是要排序,问题在于对start排序还是对end排序呢?

这题最好按照end来排,按照start排有bug,比如 [ [1,4], [2,3], [3,4] ]
 * the interval with early start might be very long and incompatible with many intervals
 * 但是并不是说不能按照start来,按照start排就要注意是删除前面的还是当前的,就要看谁的end大

 

package l435;

import java.util.Arrays;
import java.util.Comparator;

/*
 * 最好按照end来排
 */
public class Solution {
    public int eraseOverlapIntervals(Interval[] intervals) {
        
    	Arrays.sort(intervals, new Comparator<Interval>(){
			@Override
			public int compare(Interval o1, Interval o2) {
				return o1.end - o2.end;
			}
    	});
    	
    	int rst = 0;
    	int end = Integer.MIN_VALUE;
    	for(int i=0; i<intervals.length; i++)
    		if(intervals[i].start < end) {
    			rst ++;
    		} else {
    			end = intervals[i].end;
    		}
    	
    	return rst;
    }
}

 

/*
 * 按照start来排
 */
public class CopyOfSolution {
    public int eraseOverlapIntervals(Interval[] intervals) {
        
    	Arrays.sort(intervals, new Comparator<Interval>(){
			@Override
			public int compare(Interval o1, Interval o2) {
				return o1.start - o2.start;
			}
    	});
    	
    	int rst = 0;
    	int end = Integer.MIN_VALUE;
    	for(int i=0; i<intervals.length; i++)
    		if(intervals[i].start < end) {
    			rst ++;
    			if(intervals[i].end < end)
    				end = intervals[i].end; //还不如把前面的删掉
    		} else {
    			end = intervals[i].end;
    		}
    	
    	return rst;
    }
}

 

 

 

 

 

 

 

 

Given a set of intervals, for each of the interval i, check if there exists an interval j whose start point is bigger than or equal to the end point of the interval i, which can be called that j is on the "right" of i.

For any interval i, you need to store the minimum interval j's index, which means that the interval j has the minimum start point to build the "right" relationship for interval i. If the interval j doesn't exist, store -1 for the interval i. Finally, you need output the stored value of each interval as an array.

Note:

  1. You may assume the interval's end point is always bigger than its start point.
  2. You may assume none of these intervals have the same start point.

 

Example 1:

Input: [ [1,2] ]

Output: [-1]

Explanation: There is only one interval in the collection, so it outputs -1.

 

Example 2:

Input: [ [3,4], [2,3], [1,2] ]

Output: [-1, 0, 1]

Explanation: There is no satisfied "right" interval for [3,4].
For [2,3], the interval [3,4] has minimum-"right" start point;
For [1,2], the interval [2,3] has minimum-"right" start point.

 

Example 3:

Input: [ [1,4], [2,3], [3,4] ]

Output: [-1, 2, -1]

Explanation: There is no satisfied "right" interval for [1,4] and [3,4].
For [2,3], the interval [3,4] has minimum-"right" start point.

 

思路:巧在用TreeMap

/*
 * 毫无疑问是要排序减低计算量的,但是要保存在原始数组中的位置
 * 要么对Interval进行封装再排序,要么就用TreeMap
 * 
 * 用TreeMap时不用重新写Compatator,自动就按照数组的第一个来排
 * ceilingKey回大于等于给定键的最小键,如果不存在这样的键,则返回 null,而且要想使用这个方法要说明成TreeMap
 * 
 * TreeMap因为要给定一个end找到下一个start要大于该end的Interval,
 * 要找的是start,所以key放的是start
 */
public class Solution {
    public int[] findRightInterval(Interval[] intervals) {
    	TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
    	for(int i=0; i<intervals.length; i++)	map.put(intervals[i].start, i);
    	
    	int[] rst = new int[intervals.length];
    	for(int i=0; i<intervals.length; i++) {
    		Integer j = map.ceilingKey(intervals[i].end);
    		rst[i] = (j == null) ? -1 : map.get(j);
    	}
    	
    	return rst;
    }
}

Python没有treemap,只能binary search了

# Definition for an interval.
import bisect
class Interval:
    def __init__(self, s=0, e=0):
        self.start = s
        self.end = e

class Solution:
    def findRightInterval(self, intervals):
        """
        :type intervals: List[Interval]
        :rtype: List[int]
        """
        d = sorted((t.start,i) for i,t in enumerate(intervals))
        res = []
        for t in intervals:
            r = bisect.bisect_left(d, (t.end,))
            res.append(d[r][1] if r<len(d) else -1)
        return res

 

 

 

 

 

 

 

 

 

 

 

 

There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it's horizontal, y-coordinates don't matter and hence the x-coordinates of start and end of the diameter suffice. Start is always smaller than end. There will be at most 104 balloons.

An arrow can be shot up exactly vertically from different points along the x-axis. A balloon with xstart and xend bursts by an arrow shot at x if xstart ≤ x ≤ xend. There is no limit to the number of arrows that can be shot. An arrow once shot keeps travelling up infinitely. The problem is to find the minimum number of arrows that must be shot to burst all balloons.

Example:

Input:
[[10,16], [2,8], [1,6], [7,12]]

Output:
2

Explanation:
One way is to shoot one arrow for example at x = 6 (bursting the balloons [2,8] and [1,6]) and another arrow at x = 11 (bursting the other two balloons).

 

思路:与前面的按end来排序的Interval相似,莫非大部分的Interval(这里隐含就是Interval)都是按照end来排序的?

 

 

package l452;

import java.util.Arrays;
import java.util.Comparator;

/*
 * 贪心
 * 贪心:按照end来排序,射箭就都是在end上,这样就是当前最贪心的选择
 */
public class Solution {
    public int findMinArrowShots(int[][] points) {
    	
    	if(points.length == 0)	return 0;
    	
        Arrays.sort(points, new Comparator<int[]>(){

			@Override
			public int compare(int[] a1, int[] a2) {
				return a1[1] - a2[1];
			}
        	
        });
        
        int rst = 1, maxReach = points[0][1];
        for(int[] p : points) {
        	if(p[0] > maxReach) {
        		rst++;
        		maxReach = p[1];
        	}
        }
        
        return rst;
    }
}

 

 

 

 

 

 

 

 

 

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

 

思路:这里要按照start来排序

 

 

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

public class Solution {
	List<Interval> rst = new ArrayList<Interval>();
    public List<Interval> merge(List<Interval> intervals) {
        if(intervals.size() == 0)	return rst;
    	
    	Collections.sort(intervals, new Comparator<Interval>(){

			@Override
			public int compare(Interval o1, Interval o2) {
				if(o1.start > o2.start)	return 1;
				if(o1.start < o2.start)	return -1;
				return 0;
			}
    		
    	});
    	
    	rst.add(intervals.get(0));
    	for(int i=1; i<intervals.size(); i++) {
    		Interval i1 = rst.get(rst.size()-1), i2 = intervals.get(i);
    		if(i1.end >= i2.start) {
    			int newStart = i1.start;
    			int newEnd = Math.max(i1.end, i2.end);
    			Interval newInterval = new Interval(newStart, newEnd);
    			rst.remove(rst.size()-1);
    			rst.add(newInterval);
    		} else {
    			rst.add(i2);
    		}
    	}
    	
    	return rst;
    }
}

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值