From f80389167755bf5c6aee2a393efb5dd5cdd1d42f Mon Sep 17 00:00:00 2001 From: zhaocchen Date: Sun, 26 Sep 2021 15:10:53 +0800 Subject: [PATCH] feat: add typescript solution to lc problem: No.0056.Merge Intervals --- .../0000-0099/0056.Merge Intervals/README.md | 21 +++++++++++++++++++ .../0056.Merge Intervals/README_EN.md | 21 +++++++++++++++++++ .../0056.Merge Intervals/Solution.ts | 16 ++++++++++++++ 3 files changed, 58 insertions(+) create mode 100644 solution/0000-0099/0056.Merge Intervals/Solution.ts diff --git a/solution/0000-0099/0056.Merge Intervals/README.md b/solution/0000-0099/0056.Merge Intervals/README.md index 6d76bc4d8d6c9..ebd9aae66ed8b 100644 --- a/solution/0000-0099/0056.Merge Intervals/README.md +++ b/solution/0000-0099/0056.Merge Intervals/README.md @@ -113,6 +113,27 @@ class Solution { } ``` +### **TypeScript** + +```ts +function merge(intervals: number[][]): number[][] { + intervals.sort((a, b) => a[0] - b[0]); + let ans: number[][] = []; + let index: number = -1; + for (let interval of intervals) { + if (index == -1 || ans[index][1] < interval[0]) { + // 保留 + ans.push(interval); + index++; + } else { + // 求交集 + ans[index][1] = Math.max(ans[index][1], interval[1]); + } + } + return ans; +}; +``` + ### **C++** ```cpp diff --git a/solution/0000-0099/0056.Merge Intervals/README_EN.md b/solution/0000-0099/0056.Merge Intervals/README_EN.md index 8b2382ea5c554..5376bd05646b7 100644 --- a/solution/0000-0099/0056.Merge Intervals/README_EN.md +++ b/solution/0000-0099/0056.Merge Intervals/README_EN.md @@ -84,6 +84,27 @@ class Solution { } ``` +### **TypeScript** + +```ts +function merge(intervals: number[][]): number[][] { + intervals.sort((a, b) => a[0] - b[0]); + let ans: number[][] = []; + let index: number = -1; + for (let interval of intervals) { + if (index == -1 || ans[index][1] < interval[0]) { + // 保留 + ans.push(interval); + index++; + } else { + // 求交集 + ans[index][1] = Math.max(ans[index][1], interval[1]); + } + } + return ans; +}; +``` + ### **C++** ```cpp diff --git a/solution/0000-0099/0056.Merge Intervals/Solution.ts b/solution/0000-0099/0056.Merge Intervals/Solution.ts new file mode 100644 index 0000000000000..9c4c06d2126fa --- /dev/null +++ b/solution/0000-0099/0056.Merge Intervals/Solution.ts @@ -0,0 +1,16 @@ +function merge(intervals: number[][]): number[][] { + intervals.sort((a, b) => a[0] - b[0]); + let ans: number[][] = []; + let index: number = -1; + for (let interval of intervals) { + if (index == -1 || ans[index][1] < interval[0]) { + // 保留 + ans.push(interval); + index++; + } else { + // 求交集 + ans[index][1] = Math.max(ans[index][1], interval[1]); + } + } + return ans; +}; \ No newline at end of file