题目:66、Plus One
题目描述
Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
解题思路
这是一道很简单的题目,如果是用C++,最好的办法就是在数组最后一位加1后,从后往前遍历数组,判断每一位是否有进位。但是用python时,我们可以用它的库函数map、reduce和函数式编程的思想,来解决这一道题。
代码
from functools import reduce
class Solution:
def plusOne(self, digits):
return list(map(int,list(str(reduce(lambda x,y:x*10+y,digits)+1))))
# reduce和lambda函数用来将list转化为int,map用于将字符列表转化为数字列表
AC截图
题目:73. Set Matrix Zeroes
题目描述
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
Follow up:
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
解题思路
这同样是一道水题,只需要遍历整个二维数组,找到0,然后把0所在的行和列都清0即可,但题目要求空间复杂度是常数级的,所以当找到0后,先把0所在的行和列上的非零元素换成一个字符,在遍历完成后,再遍历一边二维数组,将二维数组上的字符变成0
代码
class Solution:
def setZeroes(self, matrix):
for i in range(0,len(matrix)):
flag = 0
for j in range(0,len(matrix[i])):
if matrix[i][j]==0:
flag = 1
for k in range(0,len(matrix)):
if matrix[k][j]!=0:
matrix[k][j]='*'
if flag:
for j in range(0,len(matrix[i])):
if matrix[i][j]!=0:
matrix[i][j]='*'
for i in range(0,len(matrix)):
for j in range(0,len(matrix[i])):
if matrix[i][j]=='*':
matrix[i][j]=0