forked from wufenggirl/LeetCode-in-Golang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
insert-interval.go
executable file
·75 lines (59 loc) · 1.15 KB
/
insert-interval.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package problem0057
// Interval is a couple of int
type Interval struct {
Start int
End int
}
func insert(a []Interval, newItv Interval) []Interval {
lenA := len(a)
if lenA == 0 {
return []Interval{newItv}
}
if newItv.End < a[0].Start {
return append([]Interval{newItv}, a...)
}
if a[lenA-1].End < newItv.Start {
return append(a, newItv)
}
res := make([]Interval, 0, len(a))
for i := range a {
if isOverlap(a[i], newItv) {
newItv = merge(a[i], newItv)
if i == lenA-1 {
res = append(res, newItv)
}
continue
}
if a[i].End < newItv.Start {
res = append(res, a[i])
continue
}
if newItv.End < a[i].Start {
res = append(res, newItv)
res = append(res, a[i:]...)
break
}
}
return res
}
func isOverlap(a, b Interval) bool {
return (a.Start <= b.Start && b.Start <= a.End) || (a.Start <= b.End && b.End <= a.End) || (b.Start <= a.Start && a.Start <= b.End)
}
func merge(a, b Interval) Interval {
return Interval{
Start: min(a.Start, b.Start),
End: max(a.End, b.End),
}
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func max(a, b int) int {
if a > b {
return a
}
return b
}