Skip to content

Commit

Permalink
feat(leecode): 56.合并区间
Browse files Browse the repository at this point in the history
  • Loading branch information
z979054461 committed Mar 25, 2024
1 parent 2f43559 commit f8a0315
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 0 deletions.
59 changes: 59 additions & 0 deletions docs/10.LeeCode/56.合并区间.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
---
title: 56.合并区间
date: 2024-03-24
lang: 'zh-CN'
sidebar: 'auto'
categories:
- LeeCode
tags:
location: HangZhou
---

# Heading

[[toc]]

[56.合并区间](https://leetcode.cn/problems/merge-intervals/description/)

Tags: algorithms bloomberg facebook google linkedin microsoft twitter yelp array sort

Langs: c cpp csharp dart elixir erlang golang java javascript kotlin php python python3 racket ruby rust scala swift typescript

- algorithms
- Medium (49.82%)
- Likes: 2274
- Dislikes: -
- Total Accepted: 821.3K
- Total Submissions: 1.6M
- Testcase Example: '[[1,3],[2,6],[8,10],[15,18]]'

<p>以数组 <code>intervals</code> 表示若干个区间的集合,其中单个区间为 <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> 。请你合并所有重叠的区间,并返回&nbsp;<em>一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间</em>&nbsp;。</p>

<p>&nbsp;</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>示例&nbsp;2:</strong></p>

<pre>
<strong>输入:</strong>intervals = [[1,4],[4,5]]
<strong>输出:</strong>[[1,5]]
<strong>解释:</strong>区间 [1,4] 和 [4,5] 可被视为重叠区间。</pre>

<p>&nbsp;</p>

<p><strong>提示:</strong></p>

<ul>
<li><code>1 &lt;= intervals.length &lt;= 10<sup>4</sup></code></li>
<li><code>intervals[i].length == 2</code></li>
<li><code>0 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>4</sup></code></li>
</ul>

<<< @/src/LeeCode/56.合并区间.js
38 changes: 38 additions & 0 deletions src/LeeCode/56.合并区间.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* @lc app=leetcode.cn id=56 lang=javascript
*
* [56] 合并区间
*/

// @lc code=start
/**
* @param {number[][]} intervals
* @return {number[][]}
*/
var merge = function (intervals) {
if (intervals.length <= 1) {
return intervals
}

let insertion
for (let i = 1; i < intervals.length; i++) {
insertion = intervals[i]
let j = i
while (j > 0 && insertion[0] < intervals[j - 1][0]) {
intervals[j] = intervals[j - 1]
j--
}
intervals[j] = insertion
}

const result = [intervals[0]]
for (let i = 1; i < intervals.length; i++) {
if (result[result.length - 1][1] >= intervals[i][0]) {
result[result.length - 1][1] = Math.max(result[result.length - 1][1], intervals[i][1])
} else {
result.push(intervals[i])
}
}
return result
}
// @lc code=end

0 comments on commit f8a0315

Please sign in to comment.