欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > 【Hot100】LeetCode—23. 合并 K 个升序链表

【Hot100】LeetCode—23. 合并 K 个升序链表

2024/10/25 6:33:34 来源:https://blog.csdn.net/weixin_44382896/article/details/141384199  浏览:    关键词:【Hot100】LeetCode—23. 合并 K 个升序链表

目录

  • 1- 思路
    • 优先队列
  • 2- 实现
    • ⭐23. 合并 K 个升序链表——题解思路
  • 3- ACM 实现


  • 原题连接:23. 合并 K 个升序链表

1- 思路

优先队列

  • 1- 提供的数据结构:ListNode[] lists
  • 2- 由于提供的数据结构已经是有序的,不能通过指针实现是因为不知道一共要定义多少个指针来遍历链表
  • 3- 所以引出优先队列解决,将链表的数据加入 优先队列,实现排序

实现思路

PriorityQueue<ListNode> pq = new PriorityQueue<>(len,Comparator.comparingInt(a -> a.val));
  • 上述操作实际上实现了一个最小堆,每次弹出的是一个堆顶元素。
  • 如果定义的是升序优先队列,则其弹出 poll 的时候,始终是最小的元素先弹出``

2- 实现

⭐23. 合并 K 个升序链表——题解思路

在这里插入图片描述

class Solution {public ListNode mergeKLists(ListNode[] lists) {ListNode dummyHead = new ListNode(-1);ListNode cur = dummyHead;// 定义长度int len = lists.length;if(len==0){return null;}// 1.优先队列PriorityQueue<ListNode> pq = new PriorityQueue<>(len,Comparator.comparingInt(a -> a.val));// 2.先加入头for(ListNode list:lists){if(list!=null){pq.add(list);}}// 3. 处理弹出逻辑while(!pq.isEmpty()){cur.next = pq.poll();cur = cur.next;if(cur.next!=null){pq.add(cur.next);}}return dummyHead.next;}
}

3- ACM 实现

public class mergeKLists {public static class ListNode {int val;ListNode next;ListNode(int x) {val = x;next = null;}}public static ListNode mergKLists(ListNode[] lists){// 1. 求长度int len = lists.length;if(len==0){return null;}// 1. 定义 pqPriorityQueue<ListNode> pq = new PriorityQueue<>(len, Comparator.comparingInt(a -> a.val));// 2.处理头for(ListNode list:lists){if(list!=null){pq.add(list);}}ListNode dummyHead = new ListNode(-1);ListNode cur = dummyHead;// 3. 处理pqwhile(!pq.isEmpty()){cur.next = pq.poll();cur = cur.next;if(cur.next!=null){pq.add(cur.next);}}return dummyHead.next;}public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.println("数组长度");int k = scanner.nextInt();ListNode[] lists = new ListNode[k];for (int i = 0; i < k; i++) {System.out.println("输入链表长度");int n = scanner.nextInt();if (n == 0) {lists[i] = null;} else {lists[i] = new ListNode(scanner.nextInt());ListNode current = lists[i];for (int j = 1; j < n; j++) {current.next = new ListNode(scanner.nextInt());current = current.next;}}}ListNode forRes = mergKLists(lists);while(forRes!=null){System.out.print(forRes.val+" ");forRes = forRes.next;}}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com