我正在尝试合并一些重叠的“会议”间隔。
[{0, 1}, {3, 5}, {4, 8}, {10, 12}, {9, 10}]
[{0, 1}, {3, 8}, {9, 12}]
我的第一种方法是double for循环。但是,我的输出结果是:
[{3, 8}, {9, 12}]
在我的最终结果中省略了{0,1}。
type Meeting struct {
startTime int
endTime int
}
func MergeIntervals(meetings []Meeting) []Meeting {
var mergedMeetings []Meeting
for i := 0; i < len(meetings); i++ {
for j := i + 1; j < len(meetings); j++ {
var first Meeting
var second Meeting
// the meeting with the earlier start time is the "first" meeting
if meetings[i].startTime < meetings[j].startTime {
first = meetings[i]
second = meetings[j]
} else {
first = meetings[j]
second = meetings[i]
}
if first.endTime >= second.startTime {
mergedMeetings = append(mergedMeetings, Meeting{first.startTime, second.endTime})
}
}
}
return mergedMeetings
}
答案 0 :(得分:4)
例如,
package main
import (
"fmt"
"sort"
)
type Interval struct {
Lo, Hi int
}
func merge(ivs []Interval) []Interval {
m := append([]Interval(nil), ivs...)
if len(m) <= 1 {
return m
}
sort.Slice(m,
func(i, j int) bool {
if m[i].Lo < m[j].Lo {
return true
}
if m[i].Lo == m[j].Lo && m[i].Hi < m[j].Hi {
return true
}
return false
},
)
j := 0
for i := 1; i < len(m); i++ {
if m[j].Hi >= m[i].Lo {
if m[j].Hi < m[i].Hi {
m[j].Hi = m[i].Hi
}
} else {
j++
m[j] = m[i]
}
}
return append([]Interval(nil), m[:j+1]...)
}
func main() {
intervals := []Interval{{0, 1}, {3, 5}, {4, 8}, {10, 12}, {9, 10}}
merged := merge(intervals)
fmt.Println(intervals)
fmt.Println(merged)
}
游乐场:https://play.golang.org/p/13uwiQtlxPJ
输出:
[{0 1} {3 5} {4 8} {10 12} {9 10}]
[{0 1} {3 8} {9 12}]
答案 1 :(得分:0)
唯一的“追加”发生在您的以下代码段中。
model.run()
因此,看看{0,1}和其他人: