435:无重叠区间

This commit is contained in:
huangge1199 2021-09-06 13:07:58 +08:00
parent 87930c91cc
commit a9be61f016
2 changed files with 113 additions and 0 deletions

View File

@ -0,0 +1,74 @@
//给定一个区间的集合找到需要移除区间的最小数量使剩余区间互不重叠
//
// 注意:
//
//
// 可以认为区间的终点总是大于它的起点
// 区间 [1,2] [2,3] 的边界相互接触但没有相互重叠
//
//
// 示例 1:
//
//
//输入: [ [1,2], [2,3], [3,4], [1,3] ]
//
//输出: 1
//
//解释: 移除 [1,3] 剩下的区间没有重叠
//
//
// 示例 2:
//
//
//输入: [ [1,2], [1,2], [1,2] ]
//
//输出: 2
//
//解释: 你需要移除两个 [1,2] 来使剩下的区间没有重叠
//
//
// 示例 3:
//
//
//输入: [ [1,2], [2,3] ]
//
//输出: 0
//
//解释: 你不需要移除任何区间因为它们已经是无重叠的了
//
// Related Topics 贪心 数组 动态规划 排序 👍 491 👎 0
package leetcode.editor.cn;
import java.util.Arrays;
import java.util.Comparator;
//435:无重叠区间
class NonOverlappingIntervals {
public static void main(String[] args) {
//测试代码
Solution solution = new NonOverlappingIntervals().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int eraseOverlapIntervals(int[][] intervals) {
if (intervals.length == 0) {
return 0;
}
Arrays.sort(intervals, Comparator.comparingInt(interval -> interval[1]));
int num = intervals[0][1];
int count = 1;
for (int i = 1; i < intervals.length; ++i) {
if (intervals[i][0] >= num) {
++count;
num = intervals[i][1];
}
}
return intervals.length - count;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,39 @@
<p>给定一个区间的集合,找到需要移除区间的最小数量,使剩余区间互不重叠。</p>
<p><strong>注意:</strong></p>
<ol>
<li>可以认为区间的终点总是大于它的起点。</li>
<li>区间 [1,2] 和 [2,3] 的边界相互&ldquo;接触&rdquo;,但没有相互重叠。</li>
</ol>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> [ [1,2], [2,3], [3,4], [1,3] ]
<strong>输出:</strong> 1
<strong>解释:</strong> 移除 [1,3] 后,剩下的区间没有重叠。
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong> [ [1,2], [1,2], [1,2] ]
<strong>输出:</strong> 2
<strong>解释:</strong> 你需要移除两个 [1,2] 来使剩下的区间没有重叠。
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong> [ [1,2], [2,3] ]
<strong>输出:</strong> 0
<strong>解释:</strong> 你不需要移除任何区间,因为它们已经是无重叠的了。
</pre>
<div><div>Related Topics</div><div><li>贪心</li><li>数组</li><li>动态规划</li><li>排序</li></div></div><br><div><li>👍 491</li><li>👎 0</li></div>