Leetcode 挑战 Day 06 [66. Plus One]

66. Plus One


今天这一题相对单纯、简单一些,但当中也有一些小技巧和观念,还是蛮值得一看的!

题目


You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.

Increment the large integer by one and return the resulting array of digits.

Example 1:
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].

Example 2:
Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be [4,3,2,2].

Example 3:
Input: digits = [0]
Output: [1]
Explanation: The array represents the integer 0.
Incrementing by one gives 0 + 1 = 1.
Thus, the result should be [1].

Example 4:
Input: digits = [9]
Output: [1,0]
Explanation: The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].

这题的意思也相对简单明了,题目会给我们一个阵列,当中的元素是整数型态,他希望我们能够把这整个阵列当成一个整数来看,并且对其加一,最後再以阵列的型式回传。以例子来看,[2,9,9,9]会变成[3,0,0,0],[2,8,7,6] => [2,8,7,7]。

One-line in python


在python中我们可用非常简洁的写法,就能达到题目的要求,以下这段程序码的逻辑就是,先将阵列中的整数换成字串型态,接着再把他们合并,合并後再变成整数型态,再加一,而後再把这些变成字串後再变成阵列,虽然这边更正确的事要再把其中元素换回整数,不过Leetcode测资似乎没有检查到这部分。

以下为python3的程序码

class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        return list(str(int("".join([str(i) for i in digits]))+1))

Faster Solution


然而,上述那种方法虽然很容易理解,也很简洁,但对电脑来说实在是稍嫌慢了一些,因为在转换字串与合并字串,整数再转回字串,都耗费了许多时间,以下这种解法,最多只要跑一次回圈就能达成的解法,甚至有时候可以更快。

简单来说就是我们不把阵列换成整数,我们直接对阵列中的元素作处理,从最後一个开始,如果走访到的该元素是9那就变成0,而且回圈要继续,如果是9以外的数,那我们就加一,直接return当下的阵列,就是题目所求。但如果回圈全部跑完,却还没return,就代表阵列中每个元素都是9,那我们就必须阵列开头的地方插入1,这样才符合要求!

以下是C++的程序码

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        for(int i=digits.size()-1;i>-1;i--){
            if(digits[i] == 9){
                digits[i] = 0;
            }
            else{
                digits[i] = digits[i] + 1;
                return digits;
            }
         }
        digits.insert(digits.begin(), 1);
        return digits;
    }
};

<<:  【Day9】To be or Not To be?逻辑运算子

>>:  [GAS] GBC上运作的Hello world!

Day6 风生水起,观元辰宫的木

在中国古代,木头可为梁,可为柱,可为墙 所有的建筑跟木都脱不了关系,木头为建筑之根本 当然,也涵盖到...

JS let var const的不同

let 用於宣告一个「只作用在当前区块的变数」,初始值可选择性的设定。 以 let 宣告的变数,其作...

电子书阅读器上的浏览器 [Day01] 初衷与功能总览

最近这几年,电子书阅读器的技术愈来愈成熟。除了 Amazon Kindle 和 Kobo 这些老牌...

使用 Python 实作网路爬虫 part 3

实际操作 了解 requests 与 BeautifulSoup 的功能後,我们来进行整合吧!接下来...

23.unity储存文字内容(List、foreach)

今天要用List来储存记事本内的对话资料 0.和昨天一样,先准备好对话.txt 1.写脚本,先检查有...