LeetCode in Python-1. Two Sum 两数之和
题目描述
解法1、切片后查找
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in nums:
j = target - i
start_index = nums.index(i)
next_index = start_index + 1
temp_nums = nums[next_index:]
if j in temp_nums:
return [nums.index(i), next_index + temp_nums.index(j)]
注意返回值index的转换
解法2、hash字典
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dict = {}
for i in range(len(nums)):
if target - nums[i] not in dict:
dict[nums[i]] = i
else:
return [dict[target-nums[i]], i]
解法3、同2
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dict = {}
for i, num in enumerate(nums):
if target - num in dict:
return [dict[target-num], i]
dict[num] = i
借助枚举函数,方法同2
出处
1、2、https://www.bilibili.com/video/av45727557
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 452966517@qq.com
文章标题:LeetCode in Python-1. Two Sum 两数之和
文章字数:188
本文作者:Night Zhang
发布时间:2019-07-26, 16:57:01
最后更新:2019-07-26, 17:26:32
原始链接:https://night-zhang.github.io/2019/07/26/LeetCode-in-Python-1-Two-Sum-两数之和/版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。