LeetCode2.1.17 @ Plus One 数组数字加一 D1F2
2014-07-17 02:42
246 查看
Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
初始定义carry=1,来用做PlusOne。时间复杂度O(n),空间复杂度O(1)。
如果到了MSB,最坏case是全部为9,那么需要重新建立array,赋值成[1,0,0...],空间复杂度上升为O(n)。
【注意1】cuz the length may be 1,so avoid using "digits.length-2"。另外注意i--的循环,i>=0别写错,在此出过compile error
【注意2】x%10,取余实质是 x-10-10-10 直到不能再减得到的数。同理x%6
【注意3】使用x/10来表示carry,否则用if判断太复杂
【注意4】之前我的code把 if 放在循环外面,判断MSB是否进位;放在循环里面更节省资源,只要MSB之前没有进位,那么久不用构造新Array。
【后记】follow up问题:/article/1378285.html
“我觉得为什么Google喜欢的原因是后续可以问一些比较基本的扩展问题,比如可以扩展这个到两个数组相加,或者问一些OO设计,假设现在要设计一个BigInteger类,那么需要什么构造函数,然后用什么数据结构好,用数组和链表各有什么优劣势。这些问题虽然不是很难,但是可以考到一些基本的理解,所以平时准备有机会还是可以多想想哈。”
附:第一次写错的code
The digits are stored such that the most significant digit is at the head of the list.
初始定义carry=1,来用做PlusOne。时间复杂度O(n),空间复杂度O(1)。
如果到了MSB,最坏case是全部为9,那么需要重新建立array,赋值成[1,0,0...],空间复杂度上升为O(n)。
public class Solution { public int[] plusOne(int[] digits) { int carry=1;//for LSB, carry is the "PlusOne" for(int i=digits.length-1;i>=0;i--){//【注意1】 int temp=digits[i]+carry; digits[i]=temp%10;//【注意2】 carry=temp/10;//【注意3】 if(carry==0)//【注意4】 return digits; } int[] res=new int[digits.length+1]; res[0]=1; return res; } }
【注意1】cuz the length may be 1,so avoid using "digits.length-2"。另外注意i--的循环,i>=0别写错,在此出过compile error
【注意2】x%10,取余实质是 x-10-10-10 直到不能再减得到的数。同理x%6
【注意3】使用x/10来表示carry,否则用if判断太复杂
【注意4】之前我的code把 if 放在循环外面,判断MSB是否进位;放在循环里面更节省资源,只要MSB之前没有进位,那么久不用构造新Array。
【后记】follow up问题:/article/1378285.html
“我觉得为什么Google喜欢的原因是后续可以问一些比较基本的扩展问题,比如可以扩展这个到两个数组相加,或者问一些OO设计,假设现在要设计一个BigInteger类,那么需要什么构造函数,然后用什么数据结构好,用数组和链表各有什么优劣势。这些问题虽然不是很难,但是可以考到一些基本的理解,所以平时准备有机会还是可以多想想哈。”
附:第一次写错的code
public class Solution { public int[] plusOne(int[] digits) { int carry=0; for(int i=digits.length-1;i>=0;i--){ int temp=digits[i]+1+carry; if(temp%10==0){ digits[i]=temp%10; carry=1; } else{ digits[i]=temp%10; carry=0; } } if (carry==1){ int[] res=new int[digits.length+1]; res[0]=1; return res; } else{ return digits; } } }
相关文章推荐
- LeetCode WIith JS || 66. Plus One [数组存储的数据加一]
- LeetCode_66. Plus One_数组加一
- LeetCode 66. Plus One--数字数组最后一个元素加1,保持进位
- LeetCode | Plus One(数组表示的数字加1)
- LeetCode_66. Plus One_数组加一
- 【LeetCode-面试算法经典-Java实现】【154-Find Minimum in Rotated Sorted Array II(找旋转数组中的最小数字II)】
- [LeetCode]11. Plus One加一运算
- leetcode之Search in Rotated Sorted Array,剑指offer之旋转数组的最小数字
- [LeetCode] Plus One 加一运算
- 【LeetCode】- Single Number(从数组中找出只出现一次的数字)
- leetcode 66---Plus One 进位 数组
- leetcode:Remove Duplicates from Sorted Array II (允许重复一次,去掉数组多余数字)【面试算法题】
- LeetCode2.1.17(Plus One)
- leetCode 66. Plus One 数组
- leetcode:Plus One (加一)【面试算法题】
- LeetCode 136 Single Number(数组中只出现一次的数字)
- leetcode-1 Two Sum 找到数组中两数字和为指定和
- 【leetcode】在一堆每个数字都出现三次的数组中,找到那个只出现一次的数(Single Number II)
- 【leetcode】数组中找出只出现一次的数字(Single Number)
- [LeetCode] Kth Largest Element in an Array 数组中第k大的数字