File tree Expand file tree Collapse file tree 1 file changed +12
-21
lines changed Expand file tree Collapse file tree 1 file changed +12
-21
lines changed Original file line number Diff line number Diff line change 1515 */
1616
1717class MergeIntervals {
18- func merge( intervals: [ Interval ] ) -> [ Interval ] {
19- var result = [ Interval] ( )
20-
21- let intervals = intervals. sorted {
22- if $0. start != $1. start {
23- return $0. start < $1. start
24- } else {
25- return $0. end < $1. end
26- }
27- }
28-
29- for interval in intervals {
30- guard let last = result. last else {
31- result. append ( interval)
32- continue
33- }
18+ func merge( _ intervals: [ [ Int ] ] ) -> [ [ Int ] ] {
19+ let intervals = intervals. sorted { return $0 [ 0 ] < $1 [ 0 ] }
20+ var res = [ intervals [ 0 ] ]
21+
22+ for interval in intervals [ 1 ..< intervals. count] {
3423
35- if last. end < interval. start {
36- result. append ( interval)
24+ let lastEnd = res [ res. count - 1 ] [ 1 ]
25+
26+ if lastEnd < interval [ 0 ] {
27+ res. append ( interval)
3728 } else {
38- last . end = max ( last . end , interval. end )
29+ res [ res . count - 1 ] [ 1 ] = max ( res [ res . count - 1 ] [ 1 ] , interval [ 1 ] )
3930 }
4031 }
41-
42- return result
32+
33+ return res
4334 }
4435}
You can’t perform that action at this time.
0 commit comments