1. 程式人生 > 實用技巧 >23. 合併K個排序連結串列-連結串列-困難

23. 合併K個排序連結串列-連結串列-困難

問題描述

合併k個排序連結串列,返回合併後的排序連結串列。請分析和描述演算法的複雜度。

示例:

輸入:
[
1->4->5,
1->3->4,
2->6
]
輸出: 1->1->2->3->4->4->5->6

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/merge-k-sorted-lists

解答

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 
*/ //遍歷list放入陣列,再sort生成listnode。10ms class Solution { public ListNode mergeKLists(ListNode[] lists) { int len = lists.length; if(len == 0)return null; List<Integer> resList = new ArrayList<Integer>(); for(ListNode temp:lists) while(temp!=null){ resList.add(temp.val); temp
= temp.next; } Collections.sort(resList); ListNode res = new ListNode(-1), a = res; for(int i:resList){ res.next = new ListNode(i); res = res.next; } //System.out.println(resList); return a.next; } } /* //以下是連結串列做法,280ms class Solution { public ListNode mergeKLists(ListNode[] lists) { int len = lists.length; if(len == 0)return null; ListNode res = new ListNode(-1), a = res, min = new ListNode(10000000); int position, i; while(true){ position = -1; for(i=0;i<len;i++){ if(lists[i] != null && min.val >= lists[i].val){ min = lists[i]; position = i;//記錄位置 } } if(position == -1)return a.next; lists[position] = min.next; res.next = min; res = res.next; min = new ListNode(10000000); } } }
*/