Skip to content

Commit 40d08ae

Browse files
aQuaaQua
aQua
authored and
aQua
committed
56 添加快排后,删除了冗余的代码
1 parent 1576aff commit 40d08ae

File tree

2 files changed

+11
-38
lines changed

2 files changed

+11
-38
lines changed

Algorithms/0056.merge-intervals/merge-intervals.go

Lines changed: 11 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -8,54 +8,37 @@ type Interval struct {
88
End int
99
}
1010

11-
func merge(intervals []Interval) []Interval {
12-
if len(intervals) <= 1 {
13-
return intervals
11+
func merge(its []Interval) []Interval {
12+
if len(its) <= 1 {
13+
return its
1414
}
1515

16-
quickSort(intervals)
16+
quickSort(its)
1717

18-
res := make([]Interval, 0, len(intervals))
19-
temp := intervals[0]
18+
res := make([]Interval, 0, len(its))
19+
temp := its[0]
2020

21-
for i := 1; i < len(intervals); i++ {
22-
if isOverlap(temp, intervals[i]) {
23-
temp = mergeInterval(temp, intervals[i])
21+
for i := 1; i < len(its); i++ {
22+
if its[i].Start <= temp.End {
23+
temp.End = max(temp.End, its[i].End)
2424
continue
2525
}
2626
res = append(res, temp)
27-
temp = intervals[i]
27+
temp = its[i]
2828
}
2929

3030
res = append(res, temp)
3131

3232
return res
3333
}
3434

35-
func isOverlap(a, b Interval) bool {
36-
return (a.Start <= b.Start && b.Start <= a.End) || (a.Start <= b.End && b.End <= a.End)
37-
}
38-
39-
func mergeInterval(a, b Interval) Interval {
40-
return Interval{
41-
Start: min(a.Start, b.Start),
42-
End: max(a.End, b.End),
43-
}
44-
}
45-
46-
func min(a, b int) int {
47-
if a < b {
48-
return a
49-
}
50-
return b
51-
}
52-
5335
func max(a, b int) int {
5436
if a > b {
5537
return a
5638
}
5739
return b
5840
}
41+
5942
func quickSort(is []Interval) {
6043
if len(is) <= 1 {
6144
return
@@ -68,15 +51,13 @@ func quickSort(is []Interval) {
6851
quickSort(is[j+1:])
6952
}
7053

71-
//partition 要考虑好,当a.Len()==2时,如何排好序
7254
func partition(is []Interval) int {
7355
i, j := 1, len(is)-1
7456
for {
7557
for is[0].Start >= is[i].Start && i < len(is)-1 {
7658
i++
7759
}
7860
for is[j].Start >= is[0].Start && j > 0 {
79-
8061
j--
8162
}
8263
if i >= j {

Algorithms/0056.merge-intervals/merge-intervals_test.go

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -103,14 +103,6 @@ func Test_Problem0056(t *testing.T) {
103103
}
104104
}
105105

106-
func Test_min(t *testing.T) {
107-
ast := assert.New(t)
108-
109-
actual := min(1, 0)
110-
expected := 0
111-
ast.Equal(expected, actual)
112-
}
113-
114106
func Test_max(t *testing.T) {
115107
ast := assert.New(t)
116108

0 commit comments

Comments
 (0)