table of Contents
054 Spiral Matrix
Title description
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
Problem solving method
violence
python code
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if matrix is None or len(matrix) == 0:
return matrix
m, n = len(matrix), len(matrix[0])
return self.get_spiralOrder(matrix, 0, m - 1, 0, n - 1)
def get_spiralOrder(self, matrix, r_start, r_end, c_start, c_end):
if r_start > r_end or c_start > c_end:
return []
elif r_start == r_end:
return matrix[r_start][c_start:c_end + 1]
elif c_start == c_end:
return [matrix[j][c_end] for j in range(r_start, r_end + 1)]
curr = matrix[r_start][c_start:c_end + 1] + [matrix[j][c_end] for j in range(r_start + 1, r_end)] +\
matrix[r_end][c_start:c_end + 1][::-1] +\
[matrix[j][c_start] for j in reversed(range(r_start + 1, r_end))]
res = curr + self.get_spiralOrder(matrix, r_start + 1, r_end - 1, c_start + 1, c_end - 1)
return res
059 Spiral Matrix
Title description
给定一个正整数 n,生成一个包含 1 到 n^2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
Problem solving method
violence
python code
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
res = [[0] * n for _ in range(n)]
pos = [0, 0]
move = (0, 1)
for index in range(1, n * n + 1):
res[pos[0]][pos[1]] = index
if res[(pos[0] + move[0]) % n][(pos[1] + move[1]) % n] > 0:
# (0, 1) -> (1, 0) -> (0, -1) -> (-1, 0)
move = (move[1], -1 * move[0])
pos[0] = pos[0] + move[0]
pos[1] = pos[1] + move[1]
return res
if __name__ == '__main__':
# begin
s = Solution()
print s.generateMatrix(2)
061 Rotating Linked List
Title description
# 给定一个链表,旋转链表,将链表每个节点向右移动 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
Problem solving method
violence
python code
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head or k == 0:
return head
slow = fast = head
length = 1
while k and fast.next:
fast = fast.next
length += 1
k -= 1
if k != 0:
k = (k + length - 1) % length # original k % length
return self.rotateRight(head, k)
else:
while fast.next:
fast = fast.next
slow = slow.next
return self.rotate(head, fast, slow)
def rotate(self, head, fast, slow):
fast.next = head
head = slow.next
slow.next = None
return head