【貪心】B038_LC_刪除被覆蓋區間(排序)

一、Problem

Given a list of intervals, remove all intervals that are covered by another interval in the list. Interval [a,b) is covered by interval [c,d) if and only if c <= a and b <= d.

After doing so, return the number of remaining intervals.

Input: intervals = [[1,4],[3,6],[2,8]]
Output: 2
Explanation: Interval [3,6] is covered by [2,8], therefore it is removed.

Constraints:

1 <= intervals.length <= 1000
0 <= intervals[i][0] < intervals[i][1] <= 10^5
intervals[i] != intervals[j] for all i != j

二、Solution

方法一:貪心

Q:如何排序才能讓需要檢查條件減少?

A:按區間的起點升序,按區間終點降序後,因爲起點是升序的了,所以只需要檢查區間的結尾的大小關係。

class Solution {
    public int removeCoveredIntervals(int[][] a) {
    	int n = a.length;
    	Arrays.sort(a, (e1, e2) -> {
    		if (e1[0] == e2[0])
    			return e2[1] - e1[1];
    		return e1[0] - e2[0];
    	});
    	int delete = 0, maxEnd = a[0][1];
    	for (int i = 1; i < n; i++) {
    		if (a[i][1] <= maxEnd) delete++;
    		else 				   maxEnd = a[i][1]; 
    	}
    	return n - delete;
    }
}

複雜度分析

  • 時間複雜度:O(nlogn)O(nlogn)
  • 空間複雜度:O(1)O(1)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章