-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0023_Merge_k_Sorted_Lists.java
103 lines (84 loc) · 2.83 KB
/
0023_Merge_k_Sorted_Lists.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/*
* 23. Merge k Sorted Lists
* Problem Link: https://leetcode.com/problems/merge-k-sorted-lists/
* Difficulty: Hard
*
* Solution Created by: Muhammad Khuzaima Umair
* LeetCode : https://leetcode.com/mkhuzaima/
* Github : https://github.com/mkhuzaima
* LinkedIn : https://www.linkedin.com/in/mkhuzaima/
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) return null;
return mergeListsHelper(lists, 0, lists.length - 1);
}
private ListNode mergeListsHelper(ListNode[] lists, int start, int end) {
int mid = (start + end) / 2;
if (start >= end) return lists[start];
ListNode first = mergeListsHelper(lists, start, mid);
ListNode second = mergeListsHelper(lists, mid+1, end);
return merge2Lists(first, second);
}
private ListNode merge2Lists(ListNode first, ListNode second) {
// make dummy node for easier addition
ListNode head = new ListNode(-1);
ListNode tail = head;
while (first != null && second != null) {
if (first.val < second.val) {
tail.next = first;
first = first.next;
}
else {
tail.next = second;
second = second.next;
}
tail = tail.next;
}
// only 1 of the following if will run
if (first != null) {
tail.next = first;
}
if (second != null) {
tail.next = second;
}
return head.next;
}
//////////////////////////////////// SECOND APPROACH
/*
public ListNode mergeKLists(ListNode[] lists) {
// create a list object for merged lists
ListNode head = null;
ListNode tail = null;
while (true) {
// find the minimum elment from lists
int minNodeIndex = -1;
// minimum can also be fined using Priority Queue
// but PrioriryQueue will use extra space
for (int i = 0; i < lists.length; i++) {
if (lists[i] == null) continue;
if (
minNodeIndex == -1 || // not initialized
lists[i].val < lists[minNodeIndex].val
){
minNodeIndex = i;
}
}
if (minNodeIndex == -1) {
break; // all lists are merged
}
else {
if ( head == null ) {
head = tail = lists[minNodeIndex];
}
else {
tail.next = lists[minNodeIndex];
tail = tail.next;
}
lists[minNodeIndex] = lists[minNodeIndex].next;
}
}
return head;
}
*/
}