2. Add Two Numbers(Leetcode)
生活随笔
收集整理的這篇文章主要介紹了
2. Add Two Numbers(Leetcode)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.方法一:數(shù)學(xué)加減法
1、結(jié)果存儲:建立一個結(jié)果節(jié)點和一個結(jié)果節(jié)點的引用,一個用來存結(jié)果,一個方便放回結(jié)果。以后返回值是鏈表都設(shè)置兩個鏈表存儲
2、時間復(fù)雜度:O(max(m,n)) 空間復(fù)雜度:O(max(m,n))+1。+1是因為相加后可能有進(jìn)位
3、循環(huán)遞歸的區(qū)別:
循環(huán):重復(fù)執(zhí)行同一個代碼。
可能不能解決所有問題。
遞歸:自己調(diào)用自己。就像一個小孩上樓取東西。臺階的結(jié)構(gòu)是一樣的,小孩一層一層爬樓梯直到取到東西再跑下來。
優(yōu)點:代碼更簡潔清晰,可讀性更好。
缺點:由于遞歸需要系統(tǒng)堆棧,所以空間消耗要比非遞歸代碼要大很多。而且,如果遞歸深度太大,可能系統(tǒng)撐不住。
4、當(dāng)做條件判斷和條件循環(huán)的時候,一定要考慮出判斷和循環(huán)后是否還有什么情況是需要計算的,
?
運行時間:31 ms
?
轉(zhuǎn)載于:https://www.cnblogs.com/shaer/p/10399671.html
總結(jié)
以上是生活随笔為你收集整理的2. Add Two Numbers(Leetcode)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PAT A1015
- 下一篇: ajax hash调用实例