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

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 = 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 实现如下

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)

相关推荐
计算机小白一个39 分钟前
蓝桥杯 Java B 组之设计 LRU 缓存
java·算法·蓝桥杯
万事可爱^1 小时前
HDBSCAN:密度自适应的层次聚类算法解析与实践
算法·机器学习·数据挖掘·聚类·hdbscan
大数据追光猿3 小时前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法
Dream it possible!3 小时前
LeetCode 热题 100_在排序数组中查找元素的第一个和最后一个位置(65_34_中等_C++)(二分查找)(一次二分查找+挨个搜索;两次二分查找)
c++·算法·leetcode
夏末秋也凉3 小时前
力扣-回溯-46 全排列
数据结构·算法·leetcode
南宫生3 小时前
力扣每日一题【算法学习day.132】
java·学习·算法·leetcode
柠石榴4 小时前
【练习】【回溯No.1】力扣 77. 组合
c++·算法·leetcode·回溯
Leuanghing4 小时前
【Leetcode】11. 盛最多水的容器
python·算法·leetcode
qy发大财4 小时前
加油站(力扣134)
算法·leetcode·职场和发展
王老师青少年编程4 小时前
【GESP C++八级考试考点详细解读】
数据结构·c++·算法·gesp·csp·信奥赛