21. Merge Two Sorted Lists
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode dummy = new ListNode(-1); ListNode cur = dummy; while( l1 != null && l2 != null){ if( l1.val <= l2.val){ cur.next = l1; l1 = l1.next; }else{ cur.next = l2; l2 = l2.next; } cur = cur.next; } if(l1 == null){ cur.next = l2; }else{ cur.next = l1; } return dummy.next; } }
21. Merge Two/ k Sorted Lists //classic iterate public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode dummy = new ListNode(0);//dummy ListNode p = dummy; while (l1 != null && l2 != null) { if (l1.val < l2.val) { p.next = l1; l1 = l1.next; } else { p.next = l2; l2 = l2.next; } p = p.next; } if (l1 != null) p.next = l1; if (l2 != null) p.next = l2; return dummy.next; } //recursive public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) return l2; if (l2 == null) return l1; if (l1.val < l2.val) { l1.next = mergeTwoLists(l1.next, l2); return l1; } else { l2.next = mergeTwoLists(l2.next, l1); return l2; } } 23. Merge k Sorted Lists // https://leetcode.com/problems/merge-k-sorted-lists/ Solution 1: PriorityQueue Time: O(nlogk), Space: O(k) public ListNode mergeKLists(ListNode[] lists) { if (lists == null || lists.length == 0) return null; PriorityQueue<ListNode> pq = new PriorityQueue<>(new Comparator<ListNode>(){ public int compare(ListNode n1, ListNode n2) { return n1.val - n2.val; } }); for (ListNode node : lists) if (node != null) pq.offer(node); ListNode dummy = new ListNode(0), tail = dummy; while (!pq.isEmpty()) { tail.next = pq.poll(); tail = tail.next; if (tail.next != null) pq.offer(tail.next); } return dummy.next; } Solution 2: K-Merge Sort Time: O(nlogk), Space: O(1) public ListNode mergeKLists(ListNode[] lists) { if (lists == null || lists.length == 0) return null; return mergeKLists(lists, 0, lists.length - 1); } private ListNode mergeKLists(ListNode[] lists, int start, int end) { if (start == end) return lists[start]; if (start < end){ int mid = (end - start) / 2 + start; ListNode left = mergeKLists(lists, start, mid); ListNode right = mergeKLists(lists, mid + 1, end); return mergeTwoLists(left, right); } return null; } 记住 list.subList(int fromIndex, int toIndex) 方法
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
posted on 2018-07-18 09:21 猪猪🐷 阅读(75) 评论(0) 收藏 举报
浙公网安备 33010602011771号