(1)48. Rotate Image
题目:
分析:
本题旨在对矩阵进行转置,首先用新变量myList对列表matrix进行深复制,确保在后面对matrix进行赋值时不会影响myList的值,对matrix进行两层循环,matrix的第i行第j列对应myList的第(len1-1-j)行第i列,依次进行赋值。
代码:
class Solution:
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
len1 = len(matrix)
i=0
j=0
k=0
myList=[]
#必须进行深复制,使得两个变量不会指向同一个列表,防止后面赋值出错
for item in matrix:
tmp = item[:]
myList.append(tmp)
while i < len1:
j=0
while j < len1:
matrix[i][j] = myList[len1-1-j][i]
j = j+1
i = i+1
print (matrix)
(2)75.Sort Colors
题目:
分析:
采用快排思想,循环遍历nums,令mid=0,比较nums[mid]的值,如果值为1,则mid+=1,如果值为0,则nums[mid]与nums[first]交换,并且first+=1,mid+=1,如果值为2,则nums[mid]与nums[last]交换,并且last-=1,直到mid==last结束循环。
代码:
class Solution:
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
first = 0
last = len(nums)-1
mid = 0
while mid <= last:
if nums[mid] == 1:
mid += 1
elif nums[mid] == 0:
tmp = nums[mid]
nums[mid] = nums[first]
nums[first] = tmp
mid += 1
first += 1
elif nums[mid] == 2:
tmp = nums[mid]
nums[mid] = nums[last]
nums[last] = tmp
last -= 1
print(nums)