【问题标题】:Leetcode Medium: Rotate a LinkedListLeetcode Medium:旋转一个链表
【发布时间】:2020-09-06 16:11:21
【问题描述】:

这是我写的,(是的,这不是最佳答案) 但有时我会遇到超时异常。

# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def rotateRight(self, head: ListNode, k: int) -> ListNode:
        if (head != None):
            while (k > 0):
                cur = head
                if (head.next == None):
                    prev = head
                else:
                    while (head.next != None):
                        prev = head
                        head = head.next
                    prev.next = None
                    head.next = cur
                k -= 1
        return head```

【问题讨论】:

    标签: python-3.x linked-list


    【解决方案1】:

    这个问题我们可以使用Floyd's Tortoise and Hare算法,效率更高一点:

    class Solution:
        def rotateRight(self, head, k):
            if not head:
                return
    
            if not head.next:
                return head
    
            curr, length = head, 1
            while curr.next:
                curr = curr.next
                length += 1
    
            k %= length
            if k == 0:
                return head
    
            slow = fast = head
            for _ in range(k):
                fast = fast.next
            while fast.next:
                slow, fast = slow.next, fast.next
    
            temp = slow.next
            slow.next = None
            fast.next = head
            head = temp
    
            return head
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-01
      • 2022-01-18
      • 1970-01-01
      • 2021-08-11
      • 1970-01-01
      • 2021-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多