高编作业(六)

题目: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截图

Plus One


题目: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
AC截图

Set Matrix Zeroes

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值