-
Notifications
You must be signed in to change notification settings - Fork 1
/
MergeTwoSortedLists.java
52 lines (37 loc) · 1.14 KB
/
MergeTwoSortedLists.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
package com.leetcode;
import java.util.PriorityQueue;
public class MergeTwoSortedLists {
//https://leetcode.com/problems/merge-two-sorted-lists/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null) return l2;
if(l2 == null) return l1;
ListNode result = new ListNode(0);
ListNode p = result;
PriorityQueue<ListNode> minHeap = new PriorityQueue<>((a, b)->(a.val - b.val));//always be <= 2 so constant space.
minHeap.offer(l1);
minHeap.offer(l2);
while(minHeap.size() >0){
ListNode next = minHeap.poll();
p.next = next;
if(next.next != null)
minHeap.offer(next.next);
p = p.next;
}
return result.next;
}
}
public class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
}