File tree Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Question Link: https://leetcode.com/problems/merge-k-sorted-lists/
3
+ */
4
+
5
+ /**
6
+ * Definition for singly-linked list.
7
+ * public class ListNode {
8
+ * public var val: Int
9
+ * public var next: ListNode?
10
+ * public init() { self.val = 0; self.next = nil; }
11
+ * public init(_ val: Int) { self.val = val; self.next = nil; }
12
+ * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
13
+ * }
14
+ */
15
+
16
+ class MergeKLists {
17
+ func mergeKLists( _ lists: [ ListNode ? ] ) -> ListNode ? {
18
+ guard lists. contains ( where: { $0 != nil } ) else { return nil }
19
+
20
+ var lists = lists
21
+
22
+ while lists. count > 1 {
23
+ var mergedLists = [ ListNode? ] ( )
24
+
25
+ for i in stride ( from: 0 , to: lists. count, by: 2 ) {
26
+ let l1 = lists [ i]
27
+ let l2 = ( i + 1 < lists. count) ? lists [ i + 1 ] : nil
28
+ mergedLists. append ( self . merge ( l1: l1, l2: l2) )
29
+ }
30
+ lists = mergedLists
31
+ }
32
+
33
+ return lists. first!
34
+ }
35
+
36
+ func merge( l1: ListNode ? , l2: ListNode ? ) -> ListNode ? {
37
+ var dummy = ListNode ( )
38
+ var tail : ListNode ? = dummy
39
+ var l1 = l1
40
+ var l2 = l2
41
+
42
+ while l1 != nil && l2 != nil {
43
+ if l1!. val < l2!. val {
44
+ tail? . next = l1
45
+ l1 = l1? . next
46
+ } else {
47
+ tail? . next = l2!
48
+ l2 = l2? . next
49
+ }
50
+ tail = tail? . next
51
+ }
52
+
53
+ if l1 != nil {
54
+ tail? . next = l1
55
+ }
56
+ if l2 != nil {
57
+ tail? . next = l2
58
+ }
59
+
60
+ return dummy. next
61
+ }
62
+ }
You can’t perform that action at this time.
0 commit comments