Day07
54. 螺旋矩阵 (Medium)
54. 螺旋矩阵 (Medium)
"""
给定一个包含m x n个元素的矩阵(m行, n列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例2:
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
"""
from typing import List
class Solution(object):
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
res = []
while matrix:
res += matrix.pop(0)
matrix = list(map(list, zip(*matrix)))[::-1]
return res
59. 螺旋矩阵 II (Medium)
59. 螺旋矩阵 II (Medium)
"""
给定一个正整数n,生成一个包含 1 到n2所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
"""
from typing import List
class Solution(object):
def generateMatrix(self, n: int) -> List[List[int]]:
"""
:type n: int
:rtype: List[List[int]]
"""
r, n = [[n**2]], n**2
while n > 1:
n, r = n - len(r), [[*range(n - len(r), n)]] + [*zip(*r[::-1])]
return r
61. 旋转链表 (Medium)
61. 旋转链表 (Medium)
"""
给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
示例 1:
输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL
示例 2:
输入: 0->1->2->NULL, k = 4
输出: 2->0->1->NULL
解释:
向右旋转 1 步: 2->0->1->NULL
向右旋转 2 步: 1->2->0->NULL
向右旋转 3 步: 0->1->2->NULL
向右旋转 4 步: 2->0->1->NULL
"""
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def rotateRight(self, head: ListNode, k: int) -> ListNode:
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
l = []
while head:
l[len(l):], head = [head], head.next
if l:
l[-1].next, l[-1 - k % len(l)].next = l[0], None
return l[- k % len(l)] if l else None
参考资料
1
2