ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[LeetCode] 23. Merge k Sorted Lists

2021-12-28 07:33:40  阅读:171  来源: 互联网

标签:ListNode val list lists next PriorityQueue Merge Sorted LeetCode


You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.

Example 1:

Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
  1->4->5,
  1->3->4,
  2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6

Example 2:

Input: lists = []
Output: []

Example 3:

Input: lists = [[]]
Output: []

Constraints:

  • k == lists.length
  • 0 <= k <= 10^4
  • 0 <= lists[i].length <= 500
  • -10^4 <= lists[i][j] <= 10^4
  • lists[i] is sorted in ascending order.
  • The sum of lists[i].length won't exceed 10^4.

这道题有一个便捷条件,就是每个list都是sorted,所以我们只需要比较几个list的当前node,每次把最小的取出,加入到结果的list里面即可。有限数目下取最小值,这个可以用PriorityQueue来实现。先把所有的ListNode的头都加到PriorityQueue里,然后取出最小的加到结果queue里,再把这个取出node的下一个node加到PriorityQueue里。
注意点:

  • PriorityQueue的格式写法,尤其是Comparator
  • Comparator的法则
    • 结果为负数,第一个比第二个靠前
    • 结果为正数,第一个比第二个靠后
    • 结果为0,两个排序不分先后
  • 加入PriorityQueue的时候要注意检查是不是null
  • 我比较喜欢加入一个dummy node来帮助返回。
/**
 * Definition for singly-linked list.
 * 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; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) {
            return null;
        }
        
        ListNode dummy = new ListNode(0);
        ListNode head = dummy;
        
        PriorityQueue<ListNode> pq = new PriorityQueue<ListNode>(lists.length, 
            new Comparator<ListNode>(){
                public int compare(ListNode o1, ListNode o2) {
                    return o1.val - o2.val;
                }
            });
        
        for (int i = 0; i < lists.length; i++) {
            if (lists[i] != null) {
                pq.add(lists[i]);
            }
        }
        
        while(!pq.isEmpty()) {
            ListNode tmpMin = pq.poll();
            if (tmpMin.next != null) {
               pq.add(tmpMin.next); 
            }
            head.next = tmpMin;
            head = tmpMin;
        }
        return dummy.next;
    }
    
}

标签:ListNode,val,list,lists,next,PriorityQueue,Merge,Sorted,LeetCode
来源: https://www.cnblogs.com/codingEskimo/p/15739162.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有