python-3.x - Leetcode Medium:旋转一个链表
问题描述
这是我写的,(是的,这不是最佳答案)但有时我会遇到超时异常。
# 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```
解决方案
对于这个问题,我们可以使用Floyd 的 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
推荐阅读
- java - 文件移动到另一台计算机时出现“实例化 servlet 类”错误
- mongodb - Symfony 4 / MongoDB / Docker 保存数据时的多个条目
- java - Selenium java 3.141.59 - WebDriver 和 FirefoxDriver 问题
- python-3.x - 如何使用 Python 和 WC-API 从 WooCommerce 软件插件中获取 api 信息
- python - 用networkx计算最短路径
- r - 如何修复 cpcbp 中文件(con,“r”)中的错误
- sql - 在 SQL 中插入重复值
- wordpress - 在 Smart Slider Carousel 上使活动幻灯片稍大
- php - 使用 Angular6-Yii2 上传图片和文字
- python - 在numpy中查找第一个非零行