54.螺旋矩阵
不知道为什么这种题会上腾讯top50…个人感觉没有什么意义,模拟处理边界就可以了。
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix:
return []
row, col = len(matrix), len(matrix[0])
left, right = 0, col - 1
top, bottom = 0, row - 1
ans = []
while left <= right and top <= bottom:
for c in range(left, right + 1): # 上(左→右)
ans.append(matrix[top][c])
top += 1
for r in range(top, bottom + 1): # 右(上→下)
ans.append(matrix[r][right])
right -= 1
for c in range(right, left - 1, -1): # 下(右→左)
ans.append(matrix[bottom][c])
bottom -= 1
for r in range(bottom, top - 1, -1): # 左(下→上)
ans.append(matrix[r][left])
left += 1
# 如果m != n的时候会多出来最中间的元素,所以取前row * col个
return ans[:row * col]
时间复杂度O(mn)
,空间复杂度O(mn)
。
55.螺旋矩阵Ⅱ
和上题一模一样(的无趣),思路参考上题吧。
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
left, right= 0, n - 1
top, bottom = 0, n - 1
ans = [[0] * n for _ in range(n)]
num ,end = 1, n * n
while num <= end:
for c in range(left, right + 1):
ans[top][c] = num
num += 1
top += 1
for r in range(top, bottom + 1):
ans[r][right] = num
num += 1
right -= 1
for c in range(right, left - 1, -1):
ans[bottom][c] = num
num += 1
bottom -= 1
for r in range(bottom, top - 1, -1):
ans[r][left] = num
num += 1
left += 1
return ans
时间复杂度O(mn)
,空间复杂度O(mn)
。
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:
if not head: # 如果链表为空,则返回
return head
# 因为k可能会超过链表的长度,所以要取余,所以要计算链表的长度
length = 0
t = head
while t:
t = t.next
length += 1
end = head # 用来标记旋转后链表的最后一个位置
k %= length
if k == 0: # 如果不需要移动,则直接返回
return head
# 向右移动k个元素,也就是最后的k个补到最前面,
# 因此end会指向第length - k个元素,所以要移动length - k - 1次
for i in range(length - k - 1):
end = end.next
# end 的下一个元素就是新的头结点(后面是原来的后半段链表)
ans = new_head = end.next
end.next = None # 标记end的下一个为None
while new_head.next: # 遍历到原来的后半段链表的最后一个元素,准备接上前半段
new_head = new_head.next
new_head.next = head # 接上前半段
return ans
时间复杂度O(n)
,空间复杂度O(1)
。