-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmerge2.go
More file actions
76 lines (64 loc) · 1.34 KB
/
Copy pathmerge2.go
File metadata and controls
76 lines (64 loc) · 1.34 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/* https://leetcode.com/problems/merge-intervals/description/
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
*/
package larray
/**
* Definition for an interval.
* type Interval struct {
* Start int
* End int
* }
*/
import "sort"
type Interval struct {
Start int
End int
}
type Intervals []Interval
func (intervals Intervals) Len() int {
return len(intervals)
}
func (intervals Intervals) Less(i, j int) bool {
return intervals[i].Start < intervals[j].Start
}
func (intervals Intervals) Swap(i, j int) {
intervals[i], intervals[j] = intervals[j], intervals[i]
}
func merge2(intervals []Interval) []Interval {
if len(intervals) <= 1 {
return intervals
}
sort.Sort(Intervals(intervals))
min := func(a, b int) int {
if a < b {
return a
}
return b
}
max := func(a, b int) int {
if a < b {
return b
}
return a
}
res := []Interval{}
var tmp *Interval
for _, interval := range intervals {
if tmp == nil {
tmp = &Interval{interval.Start, interval.End}
continue
}
if interval.Start > tmp.End {
res = append(res, *tmp)
tmp = &Interval{interval.Start, interval.End}
} else {
tmp.Start = min(tmp.Start, interval.Start)
tmp.End = max(tmp.End, interval.End)
}
}
res = append(res, *tmp)
return res
}