|
@@ -0,0 +1,65 @@
|
|
|
+package main
|
|
|
+
|
|
|
+import (
|
|
|
+ "fmt"
|
|
|
+ "sort"
|
|
|
+)
|
|
|
+
|
|
|
+func main() {
|
|
|
+ var intervals [][]int
|
|
|
+
|
|
|
+ intervals = [][]int{{1, 3}, {2, 6}, {8, 10}, {15, 18}}
|
|
|
+ printArray(merge(intervals))
|
|
|
+
|
|
|
+ intervals = [][]int{{2, 6}, {1, 3}, {15, 18}, {8, 10}}
|
|
|
+ printArray(merge(intervals))
|
|
|
+
|
|
|
+ intervals = [][]int{{1, 4}, {4, 5}}
|
|
|
+ printArray(merge(intervals))
|
|
|
+}
|
|
|
+
|
|
|
+func printArray(intervals [][]int) {
|
|
|
+ for _, vals := range intervals {
|
|
|
+ fmt.Printf("[%d, %d] ", vals[0], vals[1])
|
|
|
+ }
|
|
|
+ fmt.Println()
|
|
|
+}
|
|
|
+
|
|
|
+type Int [][]int
|
|
|
+
|
|
|
+func (INT Int) Len() int {
|
|
|
+ return len(INT)
|
|
|
+}
|
|
|
+func (INT Int) Less(i, j int) bool {
|
|
|
+ if INT[i][0] < INT[j][0] {
|
|
|
+ return true
|
|
|
+ }
|
|
|
+ return false
|
|
|
+}
|
|
|
+func (INT Int) Swap(i, j int) {
|
|
|
+ var temp = INT[i]
|
|
|
+ INT[i] = INT[j]
|
|
|
+ INT[j] = temp
|
|
|
+}
|
|
|
+
|
|
|
+func merge(intervals [][]int) [][]int {
|
|
|
+ if len(intervals) < 1 {
|
|
|
+ return intervals
|
|
|
+ }
|
|
|
+ var ans [][]int
|
|
|
+ sort.Sort(Int(intervals))
|
|
|
+
|
|
|
+ var left, right int = intervals[0][0], intervals[0][1]
|
|
|
+ for i := 1; i < len(intervals); i++ {
|
|
|
+ if intervals[i][0] > right {
|
|
|
+ ans = append(ans, []int{left, right})
|
|
|
+ left, right = intervals[i][0], intervals[i][1]
|
|
|
+ continue
|
|
|
+ }
|
|
|
+ if intervals[i][1] > right {
|
|
|
+ right = intervals[i][1]
|
|
|
+ }
|
|
|
+ }
|
|
|
+ ans = append(ans, []int{left, right})
|
|
|
+ return ans
|
|
|
+}
|