6

LeetCode 23 - 合并 K 个升序链表

 3 years ago
source link: https://azhuge233.com/leetcode-23-%e5%90%88%e5%b9%b6-k-%e4%b8%aa%e5%8d%87%e5%ba%8f%e9%93%be%e8%a1%a8/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

LeetCode 23Skip to content

仅记录,使用顺序合并,不包括分治和小顶堆(优先队列)

时间224ms,空间 28.8 MB(看脸)

  1. 新建链表节点 res 作为答案链表的根节点
  2. 顺序遍历数组,使用 p 指针遍历数组中的每个链表
    • p 指针遍历链表时,向 res 中添加链表元素
  3. 使用前后指针 q1 和 q2 确定添加位置
    • q1 在前 q2 在后,当 q1.val 大于或等于 p.val 时,说明找到了 p 的位置(q1 和 q2 之间),此时将 q2 的下一个节点的 val 设置为 p.val、next 指向 q1 即可入链
    • 入链时需要 new 新的链表元素,直接使用 p 指针会导致重复链/断链
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
public class Solution {
public ListNode MergeKLists(ListNode[] lists) {
int n = lists.Length;
if(n == 0) return null;
ListNode resRoot = new ListNode(val: -10001); //链的根
for(int i = 0; i < n; i++) { //遍历链数组
ListNode p = lists[i], q1, q2;
while(p != null) { //遍历每个链
q1 = resRoot.next; //前指针
q2 = resRoot; //后指针
while(q1 != null) { //寻找位置
if(q1.val == p.val || q1.val > p.val) break;
q1 = q1.next;
q2 = q2.next;
q2.next = new ListNode(val: p.val, next: q1); // ... -> q2 -> new ListNode(this.val = p.val) -> q1 -> ...
p = p.next;
return resRoot.next; //返回根的下一个元素
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int val=0, ListNode next=null) {
 *         this.val = val;
 *         this.next = next;
 *     }
 * }
 */
public class Solution {
    public ListNode MergeKLists(ListNode[] lists) {
        int n = lists.Length;
        if(n == 0) return null;
        ListNode resRoot = new ListNode(val: -10001); //链的根
        for(int i = 0; i < n; i++) { //遍历链数组
            ListNode p = lists[i], q1, q2;
            while(p != null) { //遍历每个链
                q1 = resRoot.next; //前指针
                q2 = resRoot; //后指针
                while(q1 != null) { //寻找位置
                    if(q1.val == p.val || q1.val > p.val) break;
                    q1 = q1.next;
                    q2 = q2.next;
                }
                q2.next = new ListNode(val: p.val, next: q1); // ... -> q2 -> new ListNode(this.val = p.val) -> q1 -> ...
                p = p.next;
            }
        }
        return resRoot.next; //返回根的下一个元素
    }
}
所有, 算法&数据结构LeetCode, 数据结构, 算法

发表评论 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

评论

显示名称 *

电子邮箱地址 *

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK