leetcode: 61. Rotate List
来源:互联网 发布:临漳干部网络管理系统 编辑:程序博客网 时间:2024/05/20 05:55
Q
Given a list, rotate the list to the right by k places, where k is non-negative.
Example:
Given 1->2->3->4->5->NULL and k = 2,return 4->5->1->2->3->NULL.
AC
# Definition for singly-linked list.class ListNode: def __init__(self, x): self.val = x self.next = Noneclass Solution(object): def rotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if not head: return None n = 0 cursor = head while cursor: cursor = cursor.next n += 1 k = k%n if k==0: return head fast = slow = head for i in range(k): if fast: fast = fast.next else: break preslow = None prefast = None while fast: prefast = fast fast = fast.next preslow = slow slow = slow.next if preslow: prefast.next = head preslow.next = None return slow else: return head# Time: O(n)# Space: O(1)# Definition for singly-linked list.class ListNode: def __init__(self, x): self.val = x self.next = None def __repr__(self): if self: return "{} -> {}".format(self.val, repr(self.next))class Solution2(object): def rotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if not head or not head.next: return head n, cur = 1, head while cur.next: cur = cur.next n += 1 cur.next = head cur, tail = head, cur for _ in xrange(n - k % n): tail = cur cur = cur.next tail.next = None return curif __name__ == "__main__": head, head.next, head.next.next, head.next.next.next, head.next.next.next.next = ListNode(1), ListNode(2), ListNode(3), ListNode(4), ListNode(5) print Solution().rotateRight(head, 2)
阅读全文
0 0
- [LeetCode]61.Rotate List
- LeetCode --- 61. Rotate List
- [Leetcode] 61. Rotate List
- [leetcode] 61.Rotate List
- [leetcode] 61. Rotate List
- leetcode 61. Rotate List
- LeetCode 61. Rotate List
- [leetcode] 61. Rotate List
- 61. Rotate List LeetCode
- leetcode 61. Rotate List
- LeetCode 61. Rotate List
- leetcode 61. Rotate List
- [LeetCode]61. Rotate List
- LeetCode 61. Rotate List
- LeetCode *** 61. Rotate List
- LeetCode 61. Rotate List
- [Leetcode]61. Rotate List
- LeetCode - 61. Rotate List
- 创建一个窗口程序(JFrame),标题栏起名为“浏览器”,有一个菜单条,有“文件”、“编辑”、“查看”3个菜单。“文件”菜单有两个菜单项,一项是“打开”,一项是“保存”,“打开”项做成子菜单,有两个菜
- OpenJ_Bailian
- Java 启动参数
- PAT 1107. Social Clusters (30)
- 滴滴第一期技术沙龙
- leetcode: 61. Rotate List
- 高数--- 一元函数微分学的几何应用
- nginx集群学习总结
- !!!!博客搬家啦!!!!!
- 搭建Lvs+nginx+keepalived+memcache+tomcat的集群
- matlab调用C程序
- 编写一个JFrame窗口,要求如下: 1.在窗口的NORTH区放置一个JPanel面板。 2.JPanel面板放置如下组件: (1)JLable标签,标签文本为“兴趣”,右边接着是三个JCheckBo
- Java运行内存监控工具使用
- Python实现将两个表格(txt格式)合并