算法leetcode|23. 合并K个升序链表(rust重拳出击)

news/2024/7/8 2:05:22

文章目录

  • 23. 合并K个升序链表:
    • 样例 1:
    • 样例 2:
    • 样例 3:
    • 提示:
  • 分析:
  • 题解:
    • rust
    • go
    • c++
    • c
    • python
    • java


23. 合并K个升序链表:

给你一个链表数组,每个链表都已经按升序排列。

请你将所有链表合并到一个升序链表中,返回合并后的链表。

样例 1:

输入:
	lists = [[1,4,5],[1,3,4],[2,6]]
	
输出:
	[1,1,2,3,4,4,5,6]
	
解释:
	链表数组如下:
	[
	  1->4->5,
	  1->3->4,
	  2->6
	]
	将它们合并到一个有序链表中得到。
	1->1->2->3->4->4->5->6

样例 2:

输入:
	lists = []
	
输出:
	[]

样例 3:

输入:
	lists = [[]]
	
输出:
	[]

提示:

  • k == lists.length
  • 0 <= k <= 104
  • 0 <= lists[i].length <= 500
  • -104 <= lists[i][j] <= 104
  • lists[i] 按 升序 排列
  • lists[i].length 的总和不超过 104

分析:

  • 面对这道算法题目,二当家的陷入了沉思。
  • 合并有序链表或者合并有序数组非常像归并排序的合并部分。
  • 递归和迭代都可以,通常递归更加简单直观,迭代更加高效。
  • 可以按顺序合并,但是这样每次只能合并掉一个链表,而用类似归并排序的分治方式则可以每次减少一半数量的链表。

题解:

rust

// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
//   pub val: i32,
//   pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
//   #[inline]
//   fn new(val: i32) -> Self {
//     ListNode {
//       next: None,
//       val
//     }
//   }
// }
impl Solution {
    pub fn merge_k_lists(mut lists: Vec<Option<Box<ListNode>>>) -> Option<Box<ListNode>> {
        fn merge(lists: &mut Vec<Option<Box<ListNode>>>, l: usize, r: usize) -> Option<Box<ListNode>> {
            fn merge_two_lists(list1: Option<Box<ListNode>>, list2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
                match (list1, list2) {
                    (None, None) => None,
                    (None, r) => r,
                    (l, None) => l,
                    (Some(mut l), Some(mut r)) => {
                        if l.val <= r.val {
                            l.next = merge_two_lists(l.next, Some(r));
                            Some(l)
                        } else {
                            r.next = merge_two_lists(Some(l), r.next);
                            Some(r)
                        }
                    }
                }
            }

            if l == r {
                return lists[l].take();
            }
            if l > r {
                return None;
            }
            let mid = (l + r) >> 1;
            return merge_two_lists(merge(lists, l, mid), merge(lists, mid + 1, r));
        }

        let l = lists.len();
        if l == 0 {
            return None;
        }
        merge(&mut lists, 0, l - 1)
    }
}

go

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func mergeKLists(lists []*ListNode) *ListNode {
    var merge func(int, int) *ListNode
	merge = func(l int, r int) *ListNode {
		var mergeTwoLists func(*ListNode, *ListNode) *ListNode
		mergeTwoLists = func(list1 *ListNode, list2 *ListNode) *ListNode {
			if nil == list1 {
				return list2
			}

			if nil == list2 {
				return list1
			}

			if list1.Val < list2.Val {
				list1.Next = mergeTwoLists(list1.Next, list2)
				return list1
			} else {
				list2.Next = mergeTwoLists(list1, list2.Next)
				return list2
			}
		}

		if l == r {
			return lists[l]
		}
		if l > r {
			return nil
		}
		mid := (l + r) >> 1
		return mergeTwoLists(merge(l, mid), merge(mid+1, r))
	}

	return merge(0, len(lists)-1)
}

c++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
private:
    ListNode *mergeTwoLists(ListNode *list1, ListNode *list2) {
        if (!list1) {
            return list2;
        }

        if (!list2) {
            return list1;
        }

        if (list1->val < list2->val) {
            list1->next = mergeTwoLists(list1->next, list2);
            return list1;
        } else {
            list2->next = mergeTwoLists(list1, list2->next);
            return list2;
        }
    }

    ListNode *merge(vector<ListNode *> &lists, int l, int r) {
        if (l == r) {
            return lists[l];
        }
        if (l > r) {
            return nullptr;
        }
        int mid = (l + r) >> 1;
        return mergeTwoLists(merge(lists, l, mid), merge(lists, mid + 1, r));
    }

public:
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        return merge(lists, 0, lists.size() - 1);
    }
};

c

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode *mergeTwoLists(struct ListNode *list1, struct ListNode *list2) {
    if (!list1) {
        return list2;
    }

    if (!list2) {
        return list1;
    }

    if (list1->val < list2->val) {
        list1->next = mergeTwoLists(list1->next, list2);
        return list1;
    } else {
        list2->next = mergeTwoLists(list1, list2->next);
        return list2;
    }
}

struct ListNode *merge(struct ListNode **lists, int l, int r) {
    if (l == r) {
        return lists[l];
    }
    if (l > r) {
        return NULL;
    }
    int mid = (l + r) >> 1;
    return mergeTwoLists(merge(lists, l, mid), merge(lists, mid + 1, r));
}

struct ListNode *mergeKLists(struct ListNode **lists, int listsSize) {
    return merge(lists, 0, listsSize - 1);
}

python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
        def merge(l: int, r: int) -> Optional[ListNode]:
            def mergeTwoLists(list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
                if list1 is None:
                    return list2
                if list2 is None:
                    return list1
                if list1.val < list2.val:
                    list1.next = mergeTwoLists(list1.next, list2)
                    return list1
                else:
                    list2.next = mergeTwoLists(list1, list2.next)
                    return list2

            if l == r:
                return lists[l]
            if l > r:
                return None
            mid = (l + r) >> 1
            return mergeTwoLists(merge(l, mid), merge(mid + 1, r))

        return merge(0, len(lists) - 1)


java

/**
 * 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) {
        return merge(lists, 0, lists.length - 1);
    }

    private ListNode merge(ListNode[] lists, int l, int r) {
        if (l == r) {
            return lists[l];
        }
        if (l > r) {
            return null;
        }
        int mid = (l + r) >> 1;
        return mergeTwoLists(merge(lists, l, mid), merge(lists, mid + 1, r));
    }

    private ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null) {
            return list2;
        }

        if (list2 == null) {
            return list1;
        }

        if (list1.val < list2.val) {
            list1.next = mergeTwoLists(list1.next, list2);
            return list1;
        } else {
            list2.next = mergeTwoLists(list1, list2.next);
            return list2;
        }
    }
}

非常感谢你阅读本文~
欢迎【点赞】【收藏】【评论】~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子:https://le-yi.blog.csdn.net/ 博客原创~



http://lihuaxi.xjx100.cn/news/413463.html

相关文章

卵巢早衰与微生物群,营养治疗新进展

卵巢早衰 卵巢早衰&#xff08;premature ovarian insufficiency&#xff0c;简称POI&#xff09;在生殖系统疾病中位居首位&#xff0c;这些疾病可能会损害多个功能系统&#xff0c;降低生活质量&#xff0c;最终剥夺女性患者的生育能力。 目前的激素替代疗法不能改善受孕或降…

基于JavaFX+Mysql实现(PC)足球联赛评分系统【100010048】

一、引言 1. 编写目的 本文档是概要设计文档的组成部分&#xff0c;编写数据库设计文档的目的是&#xff1a;明确数据库的表名、字段名等数据信息&#xff0c;用来指导后期数据库脚本的开发。本文档的读者对象是需求人员、系统设计人员、开发人员、测试人员。 2. ### 术语表 …

二苯并环辛炔-二硫键-马来酰亚胺,DBCO-SS-Maleimide,DBCO-SS-Mal

基础产品数据&#xff08;Basic Product Data&#xff09;&#xff1a; CAS号&#xff1a;N/A 中文名&#xff1a;二苯并环辛炔-二硫键-马来酰亚胺 英文名&#xff1a;DBCO-SS-Maleimide&#xff0c;DBCO-SS-Mal 详细产品数据&#xff08;Detailed Product Data&#xff09;&am…

DAP数据分析平台可视化组件开发

企业信息化建设会越来越完善&#xff0c;越来越体系化&#xff0c;当今数据时代背景下更加强调、重视数据的价值&#xff0c;以数据说话&#xff0c;通过数据为企业提升渠道转化率、改善企业产品、实现精准运营、有效运营&#xff0c;用数据来指引企业的发展。 组件使用是在DA…

Linux c编程之多进程

一、说明 在实际应用中,一个程序需要完成很多逻辑功能,有的功能(如数据处理)特别耗时,为了不影响主进程的处理速度,一般在启动一个主进程后,可以同时启动一个或多个进程,或者在需要的时候启动额外的进程去完成一些耗时的或独立的功能,这种应用编程模式叫做多进程。 多…

数据库分库分表

文章目录为什么要分库分表&#xff1f;数据切分垂直切分水平切分&#xff08;每个表的结构相同&#xff09;范围拆分取模拆分&#xff08;一般为业务主键&#xff09;分库分表带来的问题数据倾斜问题热点问题事务问题聚合查询问题分页问题非分区业务查询分库分表实现或工具hash…

通过地址偏移访问和修改类的成员变量

假设有如下类: class Test { public:int age { 100 }; }有下列两种方式访问和修改age字段。 方法一: 通过原始的地址偏移方式 Test test; // 还可以这样计算offset: // int Test::* age_p = &Test::age; // int offset = *(int*)&age_p; int offset = (size_t)&…

携程季报图解:营收69亿同比增29% 净利为2.45亿

雷递网 雷建平 12月15日携程集团有限公司&#xff08;纳斯达克&#xff1a;TCOM&#xff1b;香港联交所&#xff1a;9961&#xff09;今日发布财报。财报显示&#xff0c;携程2022年第三季度营收为69亿元&#xff0c;同比增长29%&#xff1b;净利润为2.45亿元&#xff1b;经调整…