Skip to content

Commit 24af36f

Browse files
committed
[week2] solve 21. Merge Two Sorted Lists
1 parent fdc0c0a commit 24af36f

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

merge-two-sorted-lists/bky373.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* TC: O(N)
3+
* SC: O(N)
4+
*/
5+
class Solution_21 {
6+
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
7+
if (list1 == null && list2 == null) {
8+
return null;
9+
}
10+
11+
List<Integer> nums = new ArrayList<>();
12+
13+
while (list1 != null) {
14+
nums.add(list1.val);
15+
list1 = list1.next;
16+
}
17+
while (list2 != null) {
18+
nums.add(list2.val);
19+
list2 = list2.next;
20+
}
21+
22+
Object[] arr = nums.toArray();
23+
Arrays.sort(arr);
24+
25+
ListNode head = new ListNode((int) arr[0]);
26+
ListNode curr = head;
27+
for (int i=1; i<arr.length; i++) {
28+
curr.next = new ListNode((int) arr[i]);
29+
curr = curr.next;
30+
}
31+
return head;
32+
}
33+
}

0 commit comments

Comments
 (0)