zoukankan      html  css  js  c++  java
  • 66. Plus One 数组加1

    [抄题]:

    Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

    You may assume the integer do not contain any leading zero, except the number 0 itself.

    The digits are stored such that the most significant digit is at the head of the list.

    给定 [1,2,3] 表示 123, 返回 [1,2,4].

    给定 [9,9,9] 表示 999, 返回 [1,0,0,0].

     [暴力解法]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    [思维问题]:

    不知道对进不进位如何分类。提前return就无忧了

    [一句话思路]:

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    1. 不需要对answer数组的后面若干位赋值了,初始化时自动=0。感觉是针对此题特殊的
    2. 有角标循环的时候,提前备注:0- n-1,无论正序、倒序

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    备注0 to n -1

    [复杂度]:Time complexity: O(n) Space complexity: O(n)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    [关键模板化代码]:

    for (int i = n - 1; i >= 0; i--) {
                if (digits[i] < 9) {
                    digits[i]++;
                    return digits;
                }else {
                    digits[i] = 0;
                }
            }

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

    369. Plus One Linked List dummynode要想到,两根指针也行 我还是太天真

     [代码风格] :

    public class Solution {
        /**
         * @param digits: a number represented as an array of digits
         * @return: the result
         */
        public int[] plusOne(int[] digits) {
            //not carry
            int n = digits.length;
            //0 to n-1 whenever
            for (int i = n - 1; i >= 0; i--) {
                if (digits[i] < 9) {
                    digits[i]++;
                    return digits;
                }else {
                    digits[i] = 0;
                }
            }
            //carry, need new array
            int[] answer = new int[n + 1];
            answer[0] = 1;
            return answer;
        }
    }
    View Code
  • 相关阅读:
    MongoDB查询修改操作语句命令大全
    SpringBoot读取war包jar包Resource资源文件解决办法
    linux lsof命令详解
    taskset
    POI导出excel,本地测试没问题,linux测试无法导出
    js中文乱码
    处理Account locked due to 217 failed logins的问题
    普通用户无法su到root用户
    gp数据库停止
    eclipse导入maven工程missing artifact(实际是存在的)错误解决
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8570427.html
Copyright © 2011-2022 走看看