leetcode - 1669. Merge In Between Linked Lists

Description

You are given two linked lists: list1 and list2 of sizes n and m respectively.

Remove list1's nodes from the ath node to the bth node, and put list2 in their place.

The blue edges and nodes in the following figure indicate the result:

Build the result list and return its head.

Example 1:

复制代码
Input: list1 = [10,1,13,6,9,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]
Output: [10,1,13,1000000,1000001,1000002,5]
Explanation: We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result.

Example 2:

复制代码
Input: list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004]
Output: [0,1,1000000,1000001,1000002,1000003,1000004,6]
Explanation: The blue edges and nodes in the above figure indicate the result.

Constraints:

复制代码
3 <= list1.length <= 10^4
1 <= a <= b < list1.length - 1
1 <= list2.length <= 10^4

Solution

No other comments, just do simulation.

Time complexity: o ( n 1 + n 2 ) o(n1+n2) o(n1+n2)

Space complexity: o ( 1 ) o(1) o(1)

Code

python3 复制代码
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:
        a_node, b_node = list1, list1
        b -= a - 1
        while a > 1:
            a_node = a_node.next
            a -= 1
        b_node = a_node.next
        while b > 0:
            b_node = b_node.next
            b -= 1
        a_node.next = list2
        list2_end = list2
        while list2_end.next:
            list2_end = list2_end.next
        list2_end.next = b_node
        return list1
相关推荐
重生之后端学习2 分钟前
146. LRU 缓存
java·数据结构·算法·leetcode·职场和发展
程曦曦4 分钟前
原地删除有序数组重复项:双指针法的艺术与实现
数据结构·算法·leetcode
你怎么知道我是队长5 分钟前
C语言---排序算法6---递归归并排序法
c语言·算法·排序算法
智驱力人工智能17 分钟前
景区节假日车流实时预警平台 从拥堵治理到体验升级的工程实践 车流量检测 城市路口车流量信号优化方案 学校周边车流量安全分析方案
人工智能·opencv·算法·安全·yolo·边缘计算
MicroTech202520 分钟前
微算法科技(NASDAQ :MLGO)抗量子攻击区块链共识机制:通过量子纠缠态优化节点验证流程,降低计算复杂度
科技·算法·区块链
pp起床21 分钟前
贪心算法 | part01
算法·贪心算法
梵刹古音21 分钟前
【C语言】 字符数组与多维数组
c语言·数据结构·算法
咩咩不吃草29 分钟前
机器学习不平衡数据处理三招:k折交叉验证、下采样与过采样实战
人工智能·算法·机器学习·下采样·过采样·k折交叉验证
weixin_4521595530 分钟前
模板编译期条件分支
开发语言·c++·算法
多恩Stone31 分钟前
【3DV 进阶-11】Trellis.2 数据处理与训练流程图
人工智能·pytorch·python·算法·3d·aigc·流程图