forked from yigenshutiao/Golang-algorithm-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsectionMerge.go
55 lines (46 loc) · 826 Bytes
/
sectionMerge.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package main
import (
"fmt"
"sort"
)
// Interval Definition for an interval.
type Interval struct {
Start int
End int
}
func merge(its []Interval) []Interval {
// LeetCode 56题 https://leetcode-cn.com/problems/merge-intervals/
if len(its) <= 1 {
return its
}
sort.Slice(its, func(i int, j int) bool {
return its[i].Start < its[j].Start
})
res := make([]Interval, 0, len(its))
temp := its[0]
for i := 1; i < len(its); i++ {
if its[i].Start <= temp.End {
temp.End = max(temp.End, its[i].End)
} else {
res = append(res, temp)
temp = its[i]
}
}
res = append(res, temp)
return res
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func main() {
res := merge([]Interval{
Interval{8, 10},
Interval{1, 3},
Interval{2, 6},
Interval{15, 18},
})
fmt.Println(res)
}