Skip to content

Commit 5d20dac

Browse files
committed
add solution task #56
1 parent f7874e9 commit 5d20dac

File tree

4 files changed

+70
-0
lines changed

4 files changed

+70
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,7 @@
265265
- [X] [1. Two Sum](sprint_leetcode/1)
266266
- [X] [19. Remove Nth Node From End of List](sprint_leetcode/19)
267267
- [X] [33. Search in Rotated Sorted Array](sprint_leetcode/33)
268+
- [X] [56. Merge Intervals](sprint_leetcode/56)
268269
- [X] [155. Min Stack](sprint_leetcode/155)
269270
- [X] [328. Odd Even Linked List](sprint_leetcode/328)
270271
- [X] [347. Top K Frequent Elements](sprint_leetcode/347)

sprint_leetcode/56/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# 56. Merge Intervals
2+
3+
Подробнее о задаче: [Тыц](https://leetcode.com/problems/merge-intervals/)

sprint_leetcode/56/solution.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package main
2+
3+
import (
4+
"sort"
5+
)
6+
7+
func merge(intervals [][]int) [][]int {
8+
sort.Slice(intervals, func(i, j int) bool {
9+
return intervals[i][0] < intervals[j][0]
10+
})
11+
12+
result := make([][]int, 0)
13+
14+
for _, interval := range intervals {
15+
if len(result) == 0 || result[len(result)-1][1] < interval[0] {
16+
result = append(result, interval)
17+
} else {
18+
max := result[len(result)-1][1]
19+
if result[len(result)-1][1] < interval[1] {
20+
max = interval[1]
21+
}
22+
result[len(result)-1][1] = max
23+
}
24+
}
25+
26+
return result
27+
}

sprint_leetcode/56/solution_test.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"reflect"
6+
"testing"
7+
)
8+
9+
type TestItemInput struct {
10+
nums [][]int
11+
}
12+
type TestItem struct {
13+
input TestItemInput
14+
output [][]int
15+
}
16+
17+
func TestTask(t *testing.T) {
18+
for i, v := range generateTasks() {
19+
t.Run(fmt.Sprintf("Test %d", i+1), func(t *testing.T) {
20+
res := merge(v.input.nums)
21+
if !reflect.DeepEqual(res, v.output) {
22+
t.Errorf("Wrong test.\nOutput: \n%v \nExpected: \n%v", res, v.output)
23+
}
24+
})
25+
}
26+
}
27+
28+
func generateTasks() []TestItem {
29+
return []TestItem{
30+
{
31+
input: TestItemInput{nums: [][]int{{1, 3}, {2, 6}, {8, 10}, {15, 18}}},
32+
output: [][]int{{1, 6}, {8, 10}, {15, 18}},
33+
},
34+
{
35+
input: TestItemInput{nums: [][]int{{1, 4}, {4, 5}}},
36+
output: [][]int{{1, 5}},
37+
},
38+
}
39+
}

0 commit comments

Comments
 (0)