leetcode Merge k Sorted Lists

本文详细解析了如何使用优先队列实现合并K个排序链表的算法,并通过示例代码展示了其实现过程。

题目链接

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
       public ListNode mergeKLists(ListNode[] lists) {
        int n=lists.length;
        ListNode result=new ListNode(Integer.MAX_VALUE);
        ListNode pointer=result;
        int nullListCount=0;
        boolean isNull[]=new boolean[n];


        Comparator<record> OrderIsdn=new Comparator<record>() {
            public int compare(record o1, record o2) {  
                // TODO Auto-generated method stub  
                int numbera = o1.value;  
                int numberb = o2.value;  
                if(numberb < numbera)  
                {  
                    return 1;  
                }  
                else if(numberb>numbera)  
                {  
                    return -1;  
                }  
                else  
                {  
                    return 0;  
                }  

            }  
        };

        PriorityQueue<record> priorityQueue=new PriorityQueue<Solution.record>(OrderIsdn);



        for(int i=0;i<n;i++)
        {
            if(lists[i]==null)
            {
                isNull[i]=true;
                nullListCount++;
            }
            else
            {
                priorityQueue.add(new record(lists[i].val,i));
            }
        }





        while(nullListCount!=n)
        {
            record aRecord=priorityQueue.poll();

            int Min=aRecord.value;
            int MinIndex=aRecord.index;
            pointer.next=new ListNode(Min);
            pointer=pointer.next;
            lists[MinIndex]=lists[MinIndex].next;
            if(lists[MinIndex]==null)
            {
                isNull[MinIndex]=true;
                nullListCount++;
            }
            else
            {
                priorityQueue.add(new record(lists[MinIndex].val, MinIndex));
            }
        }
        return result.next;
    }


    class record
    {
        int index;
        int value;
        record(int value,int index)
        {
            this.index=index;
            this.value=value;
        }
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值