54、螺旋矩阵
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
ret = []
if matrix == []:
return ret
ret.extend(matrix[0]) # 上侧
new = [reversed(i) for i in matrix[1:]]
if new == []:
return ret
r = self.spiralOrder([i for i in zip(*new)])
ret.extend(r)
return ret
55、螺旋矩阵2
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
res = [[0 for _ in range(n)] for _ in range(n)]
i = j = 0
b = 0
c = 1
while c <= n * n:
res[i][j] = c
if i == b and j < n - 1 - b:
j += 1
elif i < n - 1 - b and j == n - 1 - b:
i += 1
elif i == n - 1 - b and j > b:
j -= 1
elif i > b and j == b:
i -= 1
if i == b and j == b:
b += 1
i = j = b
c += 1
return res
61、旋转链表
# Definition for singly-linked list.
# 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:
curr = head
length = 0
while curr:
length += 1
curr = curr.next
if length <= 1 or k == 0 or k % length == 0:
return head
prev = head
curr = head
head_idx = length - k % length
while head_idx > 0:
head_idx -= 1
prev = curr
curr = curr.next
prev.next = None
res = curr
while curr.next:
curr = curr.next
curr.next = head
return res