python - 这里超出时间限制的原因是什么
问题描述
给定一个链表,将链表向右旋转 k 个位置,其中 k 是非负数。
这里有些例子:
Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL
Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL
代码:
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if k < 0:
return head
if head is None or head.next is None:
return head
it = head
while k != 0:
while it.next.next is not None:
it = it.next
temp = it.next
it.next = None
temp.next = head
head = temp
it = head
k -= 1
return head
上面的代码适用于k < 2000000。
失败的测试用例是 -
Last executed input:
[1,2,3]
2000000000
Error: Time Limit Exceeded
时间复杂度将是 O(k* 列表长度),对吗?
解决方案
推荐阅读
- javascript - TypeScript:获取可选属性
- laravel - Laravel - 自引用关系不起作用
- python - 使用 exec 命令在 codeigniter 中执行 python
- r - 根据另一个 sf 对象计算 sf 对象的面积
- reactjs - 在安装组件之前响应更改主体类
- excel - Excel VBA - 通过双击将特定单元格复制到新工作表,在下一个空闲行中
- javascript - 为什么这个 html/javascript 时钟不起作用?
- python-3.x - 使用 Javalang Python 库将 Java 代码制作成 AST
- go - HTTP客户端如何检测到HTTP服务器的传输连接是否断开
- python - 我可以将字符串与 AST 的某个子树匹配吗?