leetcode 66. Plus One 详解 python3

一.问题描述

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.

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

二.解题思路

题目就相当于给一个数让我们返回这个数+1之后的数,只不过这个数的每一位都是用数组来记录。

思路很明确:就是从个位数开始往高位处理,相当于从数组最后一位开始往高位处理,最后一位+1,如果加完1的话是10,要进位,这一位置0,下一位+1。迭代直到没有进位为止。要注意的就是如果进位一直进到最高位,那就得扩充数组长度了。比如说999+1=1000。

至于实现有两种思路:

一种是开新的空间每次计算一位保存一位,然后用一个变量来记录是否需要进位,一次迭代只需要处理当前位,最后返回的时候记得将数组反转才是最后的值。

时间复杂度:O(N),空间复杂度:O(N)

另一种是不开新的空间,就在原本数组上判断和改。

时间复杂度:O(N),空间复杂度:O(1)

更新:除了迭代,还可以用递归做,当练练手吧,其实主要都是处理结尾是999999的这些数字。

更多leetcode算法题解法: 专栏 leetcode算法从零到结束

三.源码

1.不开新空间

class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        n=len(digits)
        digits[-1]+=1
        for i in range(n-1):
            if digits[n-i-1]==10:
                digits[n-i-1]=0
                digits[n-i-2]+=1
            else:break
        if digits[0]==10:
            digits[0]=0
            return [1]+digits
        return digits

2.开新空间,来自leetcode demo

class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        
        # if digit is 9, we have to carry 1 to next digit
        # if carry is 1 and we are at the end of the array, we  have to add 1 in front
        
        res = []
        
        i = len(digits) - 1
        carry = 1
        
        while(i >= 0):
            if (digits[i] == 9 and carry):
                res.append(0)
                i -= 1
            else:
                res.append(digits[i] + carry)
                i -= 1
                carry = 0
                
        if (carry == 1):
            res.append(1)
            
        return res[::-1]
            

3.递归,来自:https://leetcode.com/problems/plus-one/discuss/438791/Recursive-Python-solution-(98.87-Speed-100-Memory)

class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        if digits[-1] < 9:
            digits[-1] += 1
            return digits
        elif len(digits) == 1 and digits[0] == 9:
            return [1, 0]
        else:
            digits[-1] = 0
            digits[0:-1] = self.plusOne(digits[0:-1])
            return digits
发布了218 篇原创文章 · 获赞 191 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/CSerwangjun/article/details/103331547