LeetCode第54题: 螺旋矩阵
- 使用递归一圈一圈的加入到列表中
class Solution:
def spiralOrder(self, matrix):
result = []
self.fun(matrix, 0, 0, len(matrix), len(matrix[0]), result)
return result
def fun(self, matrix, x: int, y: int, m: int, n: int, result):
if m <= 0 or n <= 0:
return
i = 0
j = 0
while j < n:
result.append(matrix[i+x][j+y])
j += 1
i += 1
j = n - 1
while i < m:
result.append(matrix[i+x][j+y])
i += 1
j -= 1
i = m - 1
while j >= 0 and m != 1:
result.append(matrix[x + i][y + j])
j -= 1
j = 0
i = m - 2
while i > 0 and n != 1:
result.append(matrix[i+x][j+y])
i -= 1
self.fun(matrix, x + 1, y + 1, m - 2, n - 2, result)
复杂度分析: 由于要遍历整个列表, 设链表m行, n列, 复杂度O(mn)
LeetCode第59题: 螺旋矩阵2
- 和上一题类似, 先创建一个二维列表, 然后一圈一圈递归打印
class Solution:
def generateMatrix(self, n: int):
result = []
for i in range(0, n):
result.append([])
for j in range(0, n):
result[i].append(0)
self.func(1, 0, 0, n, n, result)
return result
def func(self, start: int, x: int, y: int, m: int, n: int, result):
if m <= 0 or n <= 0:
return
i = 0
j = 0
while j < n:
result[x + i][y + j] = start
start += 1
j += 1
i += 1
j = n - 1
while i < m:
result[x + i][y + j] = start
start += 1
i += 1
j -= 1
i = m - 1
while j >= 0 and m != 1:
result[x + i][y + j] = start
start += 1
j -= 1
j = 0
i = m - 2
while i > 0 and n != 1:
result[x + i][y + j] = start
start += 1
i -= 1
self.func(start, x + 1, y + 1, m - 2, n - 2, result)
复杂度分析: 需要循环打印n**2个数, 所以复杂度O(n**2)
LeetCode第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 head == None:
return None
array = []
length = 1;
p = head
array.append(p)
pre = head
p = p.next
while p != None:
array.append(p)
length += 1
pre = p
p = p.next
pre.next = head
k = k % length
result = array[(length - k) % length]
pre_result = array[(length - k) % length - 1 if k != 0 else length - 1]
pre_result.next = None
return result
复杂度分析: 本算法需要遍历一次链表, 也链表长度为n, 复杂度为O(n)