LeetCode 61. 旋转链表

LeetCode 61. 旋转链表

给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。
示例 1:
在这里插入图片描述
输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]
示例 2:
在这里插入图片描述
输入:head = [0,1,2], k = 4
输出:[2,0,1]
提示:
链表中节点的数目在范围 [0, 500] 内
-100 <= Node.val <= 100
0 <= k <= 2 * 109

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        if k == 0 or not head or not head.next:
            return head
        
        _head = head
        total = 0
        while _head:
            total += 1
            _head = _head.next
        _k = k % total

        if _k == 0:
            return head

        dummy = ListNode(next=head)
        slow = fast = dummy
        while fast.next:
            if _k < 1:
                slow = slow.next
            fast = fast.next
            _k -= 1

            
        first = slow.next
        slow.next = None  # forth
        second = fast
        third = dummy.next
        dummy.next = first
        second.next = third
        
        return dummy.next

时间复杂度O(n)
空间复杂度O(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 rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        if k == 0 or not head or not head.next:
            return head

        _head = head
        total = 1
        while _head.next:
            total += 1
            _head = _head.next
        _head.next = head

        count = total - k % total
        while count:
            _head = _head.next
            count -= 1
        
        res = _head.next
        _head.next = None
        return res

时间复杂度O(n)
空间复杂度O(1)

相关推荐

  1. [leetcode] 61. 旋转

    2024-07-21 17:26:01       32 阅读
  2. LeetCode 61. 旋转

    2024-07-21 17:26:01       28 阅读
  3. 力扣61. 旋转

    2024-07-21 17:26:01       55 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-21 17:26:01       52 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-21 17:26:01       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-21 17:26:01       45 阅读
  4. Python语言-面向对象

    2024-07-21 17:26:01       55 阅读

热门阅读

  1. 看过来!看过来!python九大数据类型大整合!

    2024-07-21 17:26:01       15 阅读
  2. centos软件安装

    2024-07-21 17:26:01       20 阅读
  3. 内存屏障:程序员的“隐形护盾”

    2024-07-21 17:26:01       17 阅读
  4. 比较 WordPress 的 Baklib 和 BetterDocs

    2024-07-21 17:26:01       18 阅读
  5. npm install 出现canvas错误

    2024-07-21 17:26:01       14 阅读
  6. 作为一名程序员,怎样写出高效简洁的代码?

    2024-07-21 17:26:01       17 阅读
  7. python 爬虫技术 第02节 基础复习

    2024-07-21 17:26:01       16 阅读
  8. 如何在 Odoo 16 中设置和使用系统参数

    2024-07-21 17:26:01       16 阅读