首页 > 编程语言 > 详细

LeetCode做题记录(Python版)

时间:2019-10-26 11:51:14      阅读:63      评论:0      收藏:0      [点我收藏+]

1. 两数之和


点击查看折叠代码块

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dic = {}
        for i, x in enumerate(nums):
            dic[x] = i
        for i, x in enumerate(nums):
            if target - x in dic and dic[target - x] != i:
                return [i, dic[target - x]]

2. 两数相加


点击查看折叠代码块

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
from functools import reduce

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        x1, x2 = [], []
        while l1:
            x1.append(l1.val)
            l1 = l1.next
        while l2:
            x2.append(l2.val)
            l2 = l2.next
        x1.reverse()
        x2.reverse()
        x1 = reduce(lambda x, y: x * 10 + y, x1)
        x2 = reduce(lambda x, y: x * 10 + y, x2)
        sum = x1 + x2
        result = ListNode(None)
        k = result
        if sum == 0:
            k.next = ListNode(0)
        while sum > 0:
            result.next = ListNode(sum % 10)
            result = result.next
            sum //= 10
        return k.next

LeetCode做题记录(Python版)

原文:https://www.cnblogs.com/beginend/p/11742114.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!