写点什么

如何合并 K 个有序链表

用户头像
Skysper
关注
发布于: 2021 年 06 月 07 日

该题目在 leetcode 难度定义为困难,但算是比较容易的,基本求解的思路也是比较直接简单的。

基本求解

1、循环链表数组,从各个节点中获取最小值

2、结果链表中增加新产生的最小值节点

3、循环链表中最小值节点位置的链表节点指向下个节点位置

4、重复上述过程


/** * 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) {        ListNode head;        List<Object> minResult = findMin(lists);        head = (ListNode)minResult.get(0);                while(minResult.get(0) != null) {            int index = (int)minResult.get(1);            ListNode node = (ListNode)minResult.get(0);            lists[index] = node.next;            minResult = findMin(lists);            //将结果链表串起来            node.next = (ListNode)minResult.get(0);        }        return head;    }        private List<Object> findMin(ListNode[] lists) {        //依题目限制的最大值        int min =  10001;        ListNode node = null;        //获取最小值和最小值的索引位置        int index = 0;        for(int i = 0; i < lists.length; i++) {            if(lists[i] == null) {                continue;            }            if(lists[i].val < min) {                min = lists[i].val;                node = lists[i];                index=i;            }        }        return Arrays.asList(node, index);    }}
复制代码

扩展思路

1、使用优先队列处理排序


class Solution {    public ListNode mergeKLists(ListNode[] lists) {        if (lists==null || lists.length==0) return null;        //定义优先队列        PriorityQueue<ListNode> queue= new PriorityQueue<ListNode>(lists.length, (a,b)-> a.val-b.val);        //定义“工具”节点,无实际意义,仅方便“指针”处理        ListNode dummy = new ListNode(0);        ListNode tail=dummy;        //将现有头节点入队列        for (ListNode node:lists)            if (node!=null)                queue.add(node);        //循环处理,并不断取最小值        while (!queue.isEmpty()){            tail.next=queue.poll();            tail=tail.next;                        if (tail.next!=null)                queue.add(tail.next);        }        return dummy.next;    }}
复制代码


2、完成两个链表的合并操作(leetcode-21 题)


public ListNode mergeTwo(ListNode a, ListNode b) {  // merge twos.}
public ListNode mergeKLists(ListNode[] nodes) { ListNode result = null; //循环处理,也可以使用归并算法的思想进行处理 for(int i=0;i<nodes.length;i++) { result = mergeTwo(result, nodes[i]); } return result;}
复制代码


发布于: 2021 年 06 月 07 日阅读数: 8
用户头像

Skysper

关注

人生不在于谁更优秀,而在于谁更坚持 2016.03.29 加入

还未添加个人简介

评论

发布
暂无评论
如何合并K个有序链表