Open azl397985856 opened 5 months ago
/**
* @param {number[][]} intervals
* @return {number}
*/
var eraseOverlapIntervals = function (intervals) {
if (intervals.length === 0) return 0;
intervals.sort((a, b) => a[1] - b[1]);
const len = intervals.length;
let right = intervals[0][1];
let count = 1;
for (let i = 1; i < len; i++) {
if (intervals[i][0] >= right) {
count++;
right = intervals[i][1];
}
}
return len - count;
};
public int eraseOverlapIntervals(int[][] intervals) {
// 思路:直接按照第一位从小到大排序 然后逐个对比,如果第一位相同 移除距离最长的区间;两两比较,移除有重叠的第二位较大的那个区间
// 时间复杂度:nLongn 空间复杂度:排序所需的空间复杂度(On或者nOlogn)
/*Arrays.sort(intervals,(a,b)->a[0]-b[0]);
int count=0;
for(int i=1;i<intervals.length;i++){
if(intervals[i][0]<intervals[i-1][1]){
count++;
// 如果当前第二位大于前一个数的第二位,就删除当前值,拿前一个数和下一个数继续比较
if(intervals[i][1]>intervals[i-1][1]){
intervals[i][1]=intervals[i-1][1];
}
}
}
return count;*/
// 方法2
return erase1(intervals);
}
// 按照右端点排序,找构成不重叠区间的个数,n-此个数就是所求解
private int erase1(int[][] intervals){
if (intervals.length == 0) {
return 0;
}
Arrays.sort(intervals, new Comparator<int[]>() {
public int compare(int[] interval1, int[] interval2) {
return interval1[1] - interval2[1];
}
});
int n = intervals.length;
int right = intervals[0][1];
int ans = 1;
for (int i = 1; i < n; ++i) {
if (intervals[i][0] >= right) {
++ans;
right = intervals[i][1];
}
}
return n - ans;
}
func eraseOverlapIntervals(_ intervals: [[Int]]) -> Int {
guard intervals.count > 1 else {
return 0
}
let sortedIntervals = intervals.sorted { $0[1] < $1[1] }
var nonOverlapCount = 1
var end = sortedIntervals[0][1]
for i in 1..<sortedIntervals.count {
if sortedIntervals[i][0] >= end {
nonOverlapCount += 1
end = sortedIntervals[i][1]
}
}
return intervals.count - nonOverlapCount
}
class Solution {
public:
int eraseOverlapIntervals(vector<vector
static bool cmp (const vector<int>& a, const vector<int>& b) {
return a[1] < b[1];
}
};
435. 无重叠区间
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/non-overlapping-intervals/
前置知识
暂无
题目描述