From ef2eb4b47ab282737b8344bb4837aeb5b066dbcf Mon Sep 17 00:00:00 2001 From: Luo <82520819+Jerry-306@users.noreply.github.com> Date: Sat, 2 Oct 2021 14:02:38 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=200056=20=E5=90=88=E5=B9=B6?= =?UTF-8?q?=E5=8C=BA=E9=97=B4=20JavaScript=20=E5=8F=A6=E4=B8=80=E7=A7=8D?= =?UTF-8?q?=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...10\345\271\266\345\214\272\351\227\264.md" | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git "a/problems/0056.\345\220\210\345\271\266\345\214\272\351\227\264.md" "b/problems/0056.\345\220\210\345\271\266\345\214\272\351\227\264.md" index 93c0a2a040..fd914497ad 100644 --- "a/problems/0056.\345\220\210\345\271\266\345\214\272\351\227\264.md" +++ "b/problems/0056.\345\220\210\345\271\266\345\214\272\351\227\264.md" @@ -241,6 +241,32 @@ var merge = function (intervals) { return result }; ``` +版本二:左右区间 +```javascript +/** + * @param {number[][]} intervals + * @return {number[][]} + */ +var merge = function(intervals) { + let n = intervals.length; + if ( n < 2) return intervals; + intervals.sort((a, b) => a[0]- b[0]); + let res = [], + left = intervals[0][0], + right = intervals[0][1]; + for (let i = 1; i < n; i++) { + if (intervals[i][0] > right) { + res.push([left, right]); + left = intervals[i][0]; + right = intervals[i][1]; + } else { + right = Math.max(intervals[i][1], right); + } + } + res.push([left, right]); + return res; +}; +```