Skip to content

Commit 1576aff

Browse files
aQuaaQua
aQua
authored and
aQua
committed
56 accepted,手动实现了一遍快排
1 parent 65ff263 commit 1576aff

File tree

2 files changed

+38
-3
lines changed

2 files changed

+38
-3
lines changed

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

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package Problem0056
22

3+
import "math/rand"
4+
35
// Interval Definition for an interval.
46
type Interval struct {
57
Start int
@@ -11,6 +13,8 @@ func merge(intervals []Interval) []Interval {
1113
return intervals
1214
}
1315

16+
quickSort(intervals)
17+
1418
res := make([]Interval, 0, len(intervals))
1519
temp := intervals[0]
1620

@@ -29,7 +33,7 @@ func merge(intervals []Interval) []Interval {
2933
}
3034

3135
func isOverlap(a, b Interval) bool {
32-
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)
36+
return (a.Start <= b.Start && b.Start <= a.End) || (a.Start <= b.End && b.End <= a.End)
3337
}
3438

3539
func mergeInterval(a, b Interval) Interval {
@@ -52,3 +56,34 @@ func max(a, b int) int {
5256
}
5357
return b
5458
}
59+
func quickSort(is []Interval) {
60+
if len(is) <= 1 {
61+
return
62+
}
63+
64+
j := rand.Intn(len(is))
65+
is[0], is[j] = is[j], is[0]
66+
j = partition(is)
67+
quickSort(is[0:j])
68+
quickSort(is[j+1:])
69+
}
70+
71+
//partition 要考虑好,当a.Len()==2时,如何排好序
72+
func partition(is []Interval) int {
73+
i, j := 1, len(is)-1
74+
for {
75+
for is[0].Start >= is[i].Start && i < len(is)-1 {
76+
i++
77+
}
78+
for is[j].Start >= is[0].Start && j > 0 {
79+
80+
j--
81+
}
82+
if i >= j {
83+
break
84+
}
85+
is[i], is[j] = is[j], is[i]
86+
}
87+
is[0], is[j] = is[j], is[0]
88+
return j
89+
}

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,11 +45,11 @@ func Test_Problem0056(t *testing.T) {
4545
question{
4646
para{[]Interval{
4747
Interval{1, 4},
48-
Interval{0, 5},
48+
Interval{0, 6},
4949
},
5050
},
5151
ans{[]Interval{
52-
Interval{0, 5},
52+
Interval{0, 6},
5353
},
5454
},
5555
},

0 commit comments

Comments
 (0)