题目:
1、螺旋矩阵
2、移除链表元素
##代码实现
#螺旋矩阵
class Solution(object):
def generateMatrix(self, n):
res = [[0] * n for i in range(n)]
a = 1
# 初始化左、右、上、下边界。
left, right, up, down = 0, n - 1, 0, n - 1
while a <= n * n:
# 从左到右
for i in range(left, right + 1):
res[up][i] = a
a += 1
up += 1
# 从上到下
for i in range(up, down + 1):
res[i][right] = a
a += 1
right -= 1
# 从右到左
for i in range(right, left - 1, -1):
res[down][i] = a
a += 1
down -= 1
# 从下到上
for i in range(down, up - 1, -1):
res[i][left] = a
a += 1
left += 1
return res
#移除链表元素
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
head = f = ListNode(0, head)
while f and f.next:
while f and f.next and f.next.val == val:
f.next = f.next.next
f = f.next
return head.next