Java for LeetCode 023 Merge k Sorted Lists

來源:互聯網
上載者:User

標籤:

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

解題思路一:

之前我們有mergeTwoLists(ListNode l1, ListNode l2)方法,直接調用的話,需要k-1次調用,每次調用都需要產生一個ListNode[],空間開銷很大。如果採用分治的思想,對相鄰的兩個ListNode進行mergeTwoLists,每次將規模減少一半,直到規模變為2為止,空間開銷就會小很多。JAVA實現如下:

static public ListNode mergeKLists(ListNode[] lists) {if (lists.length == 0)return null;if (lists.length == 1)return lists[0];if (lists.length == 2)return mergeTwoLists(lists[0], lists[1]);//參考Java for LeetCode 021 Merge Two Sorted Listselse {ListNode[] halfLists = new ListNode[lists.length / 2];if (lists.length % 2 == 0)for (int i = 0; i < halfLists.length; i++)halfLists[i] = mergeTwoLists(lists[2 * i], lists[2 * i + 1]);else {for (int i = 0; i < halfLists.length; i++)halfLists[i] = mergeTwoLists(lists[2 * i], lists[2 * i + 1]);halfLists[0] = mergeTwoLists(halfLists[0],lists[lists.length - 1]);}return mergeKLists(halfLists);}}

 解題思路二:

採用優先順序隊列,JAVA實現如下:

public ListNode mergeKLists(ListNode[] lists) {Queue<ListNode> heap = new PriorityQueue<ListNode>(new Comparator<ListNode>() {public int compare(ListNode l1, ListNode l2) {return l1.val - l2.val;}});ListNode dummy = new ListNode(0), cur = dummy, tmp;for (ListNode list : lists)if (list != null)heap.offer(list);while (!heap.isEmpty()) {tmp = heap.poll();cur.next = tmp;cur = cur.next;if (tmp.next != null)heap.offer(tmp.next);}return dummy.next;}

 

Java for LeetCode 023 Merge k Sorted Lists

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.