python刷题—日常刷题

python刷题—日常刷题,第1张

python刷题—日常刷题

1.题目

https://leetcode-cn.com/problems/add-two-numbers/

2.个人题解

# 第一次完美提交,和官方答案思路一样,记录下
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def addTwonumbers(self, l1, l2) :
        new = ListNode()  # 初始化
        head = new
        temp = 0
        sums = 0
        while l1 or l2:
            if l1 and l2:
                sums = l1.val + l2.val + temp
                if sums >= 10:
                    temp = 1
                    sums = sums - 10
                else:
                    temp = 0
                l1 = l1.next
                l2 = l2.next
            elif l1 or l2:
                if temp == 0:
                    if l1:
                        new.next = l1
                        new = l1
                        l1 = None
                        break
                    elif l2:
                        new.next = l2
                        new = l2
                        l2 = None
                        break
                elif temp == 1:
                    if l1:
                        sums = l1.val + temp
                        l1 = l1.next
                    elif l2:
                        sums = l2.val + temp
                        l2 = l2.next
                    if sums >= 10:
                        temp = 1
                        sums = sums - 10
                    else:
                        temp = 0

            r = ListNode()
            r.val = sums
            sums = 0
            new.next = r
            new = r
        if not l1 and not l2 and temp:
            r = ListNode()
            r.val = 1
            new.next = r
        return head.next

# debug
debug = Solution()
l1 = ListNode(6, ListNode(1, ListNode(2)))
l2 = ListNode(4, ListNode(4))
d = debug.addTwonumbers(l1, l2)
while d:
    print(d.val)
    d = d.next

3.题目

https://leetcode-cn.com/problems/two-sum/

4.个人题解

# 查找-哈希表法
from typing import List
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        res = []
        temp = dict()
        for i, num in enumerate(nums):
            temp[num] = i
        for i, num in enumerate(nums):
            if target-num in temp.keys() and i != temp[target-num]:
                return [i, temp[target-num]]

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5721408.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存