2. Add Two Numbers(Leetcode)
生活随笔
收集整理的這篇文章主要介紹了
2. Add Two Numbers(Leetcode)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:
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.方法一:數學加減法
1、結果存儲:建立一個結果節點和一個結果節點的引用,一個用來存結果,一個方便放回結果。以后返回值是鏈表都設置兩個鏈表存儲
2、時間復雜度:O(max(m,n)) 空間復雜度:O(max(m,n))+1。+1是因為相加后可能有進位
3、循環遞歸的區別:
循環:重復執行同一個代碼。
可能不能解決所有問題。
遞歸:自己調用自己。就像一個小孩上樓取東西。臺階的結構是一樣的,小孩一層一層爬樓梯直到取到東西再跑下來。
優點:代碼更簡潔清晰,可讀性更好。
缺點:由于遞歸需要系統堆棧,所以空間消耗要比非遞歸代碼要大很多。而且,如果遞歸深度太大,可能系統撐不住。
4、當做條件判斷和條件循環的時候,一定要考慮出判斷和循環后是否還有什么情況是需要計算的,
?
運行時間:31 ms
?
轉載于:https://www.cnblogs.com/shaer/p/10399671.html
總結
以上是生活随笔為你收集整理的2. Add Two Numbers(Leetcode)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PAT A1015
- 下一篇: ajax hash调用实例