[leetcode] Merge k Sorted Lists

來源:互聯網
上載者:User

標籤:des   style   class   blog   code   java   

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

https://oj.leetcode.com/problems/merge-k-sorted-lists/

思路1(naive):1跟2合并,然後跟3合并,然後跟4合并,一直到k個合并完。

    複雜度:1,2合并訪問2n個節點,12與3合并訪問3n個節點,...,123~k-1與k合并訪問kn個節點,總共遍曆節點數目n(3+4+5+...+k),O(nk^2)。


思路2:mergeSort的思想,K個鏈表先劃分為合并兩個k/2的鏈表,每個k/2的鏈表在劃分為k/4的鏈表,一直到只剩一個或者兩個鏈表。

    複雜度:T(k)=2T(k/2)+O(nk),根據主定理(演算法導論上有講),複雜度為O(nklogk)。


思路3:維護一個大小為k的堆。每次取堆頂元素放到結果中,並把該元素的後繼(如果有)放入堆中。

    複雜度:每個元素讀取一次nk,堆操作logk,所以複雜度為O(nklogk)。

 

思路2代碼:

public ListNode mergeKLists(ArrayList<ListNode> lists) {        if (lists == null)            return null;        return merge(lists, 0, lists.size() - 1);    }    private ListNode merge(ArrayList<ListNode> lists, int start, int end) {        if (start == end)            return lists.get(start);        int mid = (start + end) / 2;        ListNode one = merge(lists, start, mid);        ListNode two = merge(lists, mid + 1, end);        return mergeTwoLists(one, two);    }    private ListNode mergeTwoLists(ListNode l1, ListNode l2) {        if (l1 == null)            return l2;        if (l2 == null)            return l1;        ListNode p1 = l1;        ListNode p2 = l2;        ListNode head = new ListNode(-1);        head.next = p1.val <= p2.val ? p1 : p2;        ListNode tail = head;        while (p1 != null && p2 != null) {            if (p1.val <= p2.val) {                tail.next = p1;                ListNode oldP1 = p1;                p1 = p1.next;                oldP1.next = null;                tail = oldP1;            } else {                tail.next = p2;                ListNode oldP2 = p2;                p2 = p2.next;                oldP2.next = null;                tail = oldP2;            }        }        if (p1 != null)            tail.next = p1;        if (p2 != null)            tail.next = p2;        return head.next;    }

 

 

 

思路3代碼(加測試代碼):

import java.util.ArrayList;import java.util.Comparator;import java.util.PriorityQueue;import java.util.Random;public class Solution {    public ListNode mergeKLists(ArrayList<ListNode> lists) {        if (lists == null)            return null;        PriorityQueue<ListNode> pq = new PriorityQueue<ListNode>(20, new Comparator<ListNode>() {            @Override            public int compare(ListNode o1, ListNode o2) {                return o1.val - o2.val;            }        });        ListNode head = new ListNode(-1);        ListNode cur = head;        for (int i = 0; i < lists.size(); i++) {            if (lists.get(i) != null)                pq.add(lists.get(i));        }        while (!pq.isEmpty()) {            ListNode out = pq.remove();            cur.next = out;            cur = cur.next;            if (out.next != null)                pq.add(out.next);        }        return head.next;    }    public static void main(String[] args) {        ArrayList<ListNode> lists = new ArrayList<ListNode>();        int k = 3;        for (int i = 0; i < k; i++) {            ListNode list = makeList(getRandomArray());            lists.add(list);            printList(list);        }        printList(new Solution().mergeKLists(lists));    }    private static int[] getRandomArray() {        Random rand = new Random();        int size = rand.nextInt(10);        int[] res = new int[size];        if (size == 0)            return res;        res[size - 1] = 100;        for (int i = size - 2; i >= 0; i--) {            res[i] = rand.nextInt(res[i + 1] + 1);        }        return res;    }    private static ListNode makeList(int[] a) {        ListNode head = new ListNode(-1);        ListNode p = head;        for (int i = 0; i < a.length; i++) {            p.next = new ListNode(a[i]);            p = p.next;        }        return head.next;    }    private static void printList(ListNode head) {        while (head != null) {            System.out.print(head.val);            if (head.next != null)                System.out.print("->");            head = head.next;        }        System.out.println();    }}class ListNode {    int val;    ListNode next;    ListNode(int x) {        val = x;        next = null;    }}

 

 

參考:

http://blog.csdn.net/linhuanmars/article/details/19899259

http://www.cnblogs.com/TenosDoIt/p/3673188.html

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.