本人菜鸟 边刷边进步
链接:https://leetcode-cn.com/playground/new/empty/
# first 2204ms
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i] + nums[j] == target:
return i,j
# second 412ms
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for index, num in enumerate(nums):
if target - num in nums and nums.index(target - num) != index:
return nums.index(target - num), index
# third 12ms
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict_ = {}
for index, num in enumerate(nums):
if target - num in dict_:
return dict_[target - num], index
dict_[num] = index
20220223
链接 https://leetcode-cn.com/problems/add-two-numbers/
这道题在ListNode()难倒了 想了很久 没弄懂,看看睡觉前能不能弄懂
下午才弄懂,自己写了个简单版
# 摘抄网友的
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
head = curr = ListNode()
carry = val = 0
while carry or l1 or l2:
val = carry
if l1: l1, val = l1.next, l1.val + val
if l2: l2, val = l2.next, l2.val + val
carry, val = divmod(val, 10)
curr.next = curr = ListNode(val)
return head.next
# my 理解 version 64ms
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
return_node = None
# 初始化进位的值
jinwei = 0
# 将结果保存起来 方便后面做逆序
result = []
while l1 or l2 or jinwei:
# 这里需要将进位的值赋值给val,加上进位的值
val = jinwei
if l1:
# 取出数据,并且l1指向l1.next
val = l1.val + jinwei
l1 = l1.next
if l2:
# 取出数据,并且l2指向l2.next
val = val + l2.val
l2 = l2.next
# 获得进位
jinwei, yushu = divmod(val, 10)
result.append(yushu)
for ii in reversed(result):
# 新建ListNode()结点
new = ListNode()
new.val = ii
new.next = return_node
# 将return_node指向new结点
return_node = new
return return_node