それでは毛玉諸君、これにて失敬

日々の精進を備忘録的に綴ります。

leetcode日記2

ジムに行きたいko_ya346です。
引き続きleetcodeやります。

addTwoNumbers

leetcode.com

  • l1, l2を掘り進んで数字を足していく
  • 繰り上がりを管理する

でAccepted!

自力解法はリストでデータを持ちつつ最後に提出用linked listを作ったけど、
模範解答は計算しつつlinked listを作っていて関心しました。
処理時間も半分以下。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
# 模範解答
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        carrying = 0
        dummyhead = ListNode(0) # ずっと最初の位置にいる用
        curr = dummyhead # ノードの先端の位置にいる用
        while l1 is not None or l2 is not None or carrying != 0:
            # print(l1, l2)
            tmp = carrying
            if l1 is not None:
                tmp += l1.val
                l1 = l1.next
            if l2 is not None:
                tmp += l2.val
                l2 = l2.next
                        
            newnode = ListNode(tmp % 10)
            curr.next = newnode
            curr = newnode
            carrying = tmp // 10
        # print(dummyhead)
        
        return dummyhead.next
  

# 自力解法
#     def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
#         carrying = 0
#         ans = []
#         while True:
#             tmp = carrying
#             if l1 is not None:
#                 tmp += l1.val
#                 l1 = l1.next
#             if l2 is not None:
#                 tmp += l2.val
#                 l2 = l2.next
                        
#             ans.append(tmp % 10)
#             if tmp // 10 >= 1:
#                 carrying = 1
#             else:
#                 carrying = 0
#             if l1 is None and l2 is None:
#                 if carrying:
#                     ans.append(carrying)
#                 break
        
#         ln = None
#         for v in ans[::-1]:
#             if ln is None:
#                 ln = ListNode(v, None)
#             else:
#                 ln = ListNode(v, ln)
#         return ln