forked from halfrost/LeetCode-Go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path57. Insert Interval.go
55 lines (47 loc) · 1.04 KB
/
57. 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
package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// Interval define
type Interval = structures.Interval
/**
* Definition for an interval.
* type Interval struct {
* Start int
* End int
* }
*/
func insert(intervals []Interval, newInterval Interval) []Interval {
res := make([]Interval, 0)
if len(intervals) == 0 {
res = append(res, newInterval)
return res
}
curIndex := 0
for curIndex < len(intervals) && intervals[curIndex].End < newInterval.Start {
res = append(res, intervals[curIndex])
curIndex++
}
for curIndex < len(intervals) && intervals[curIndex].Start <= newInterval.End {
newInterval = Interval{Start: min(newInterval.Start, intervals[curIndex].Start), End: max(newInterval.End, intervals[curIndex].End)}
curIndex++
}
res = append(res, newInterval)
for curIndex < len(intervals) {
res = append(res, intervals[curIndex])
curIndex++
}
return res
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}
func min(a int, b int) int {
if a > b {
return b
}
return a
}