56:合并区间

This commit is contained in:
huangge1199@hotmail.com 2021-09-06 19:48:30 +08:00
parent 2a3f143b2f
commit 6104eb792e
2 changed files with 104 additions and 0 deletions

View File

@ -0,0 +1,75 @@
//以数组 intervals 表示若干个区间的集合其中单个区间为 intervals[i] = [starti, endi] 请你合并所有重叠的区间并返
//回一个不重叠的区间数组该数组需恰好覆盖输入中的所有区间
//
//
//
// 示例 1
//
//
//输入intervals = [[1,3],[2,6],[8,10],[15,18]]
//输出[[1,6],[8,10],[15,18]]
//解释区间 [1,3] [2,6] 重叠, 将它们合并为 [1,6].
//
//
// 示例 2
//
//
//输入intervals = [[1,4],[4,5]]
//输出[[1,5]]
//解释区间 [1,4] [4,5] 可被视为重叠区间
//
//
//
// 提示
//
//
// 1 <= intervals.length <= 10
// intervals[i].length == 2
// 0 <= starti <= endi <= 10
//
// Related Topics 数组 排序 👍 1092 👎 0
package leetcode.editor.cn;
import com.code.leet.entiy.TwoArray;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
//56:合并区间
class MergeIntervals{
public static void main(String[] args) {
//测试代码
Solution solution = new MergeIntervals().new Solution();
// TwoArray twoArray = new TwoArray("[[1,4],[2,3]]",true);
TwoArray twoArray = new TwoArray("[[1,3],[2,6],[8,10],[15,18]]",true);
solution.merge(twoArray.getArr());
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int[][] merge(int[][] intervals) {
Arrays.sort(intervals, (o1, o2) -> o1[0]==o2[0]?o1[1]-o2[1]:o1[0]-o2[0]);
List<int[]> list = new ArrayList<>();
int[] bef = intervals[0];
for (int[] arr:intervals) {
if(arr[0]<=bef[1]){
bef[1] = Math.max(arr[1],bef[1]);
}else{
list.add(bef);
bef = arr;
}
}
list.add(bef);
int[][] result = new int[list.size()][2];
for (int i = 0; i < list.size(); i++) {
result[i] = list.get(i);
}
return result;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,29 @@
<p>以数组 <code>intervals</code> 表示若干个区间的集合,其中单个区间为 <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> 。请你合并所有重叠的区间,并返回一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间。</p>
<p> </p>
<p><strong>示例 1</strong></p>
<pre>
<strong>输入:</strong>intervals = [[1,3],[2,6],[8,10],[15,18]]
<strong>输出:</strong>[[1,6],[8,10],[15,18]]
<strong>解释:</strong>区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
</pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入:</strong>intervals = [[1,4],[4,5]]
<strong>输出:</strong>[[1,5]]
<strong>解释:</strong>区间 [1,4] 和 [4,5] 可被视为重叠区间。</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= intervals.length <= 10<sup>4</sup></code></li>
<li><code>intervals[i].length == 2</code></li>
<li><code>0 <= start<sub>i</sub> <= end<sub>i</sub> <= 10<sup>4</sup></code></li>
</ul>
<div><div>Related Topics</div><div><li>数组</li><li>排序</li></div></div><br><div><li>👍 1092</li><li>👎 0</li></div>