LeetCode 日记(#1 两数之和)
python3解答
题目内容:
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:
输入:nums = [3,2,4], target = 6
输出:[1,2]
示例 3:
输入:nums = [3,3], target = 6
输出:[0,1]
解法一:暴力搜索
最常规的想法,暴力搜索:
1.对每一个下标为i的数字num1,查找列表中 (target - num1)是否存在
2.若存在,则返回其下标j;
3.若不存在,则迭代 i = i + 1 ,开始下一轮搜索。
不够,我们考虑到,如果我们在查找的过程中,能够只查找该数字之前或只查找该数字之后的数字,可以在不错失答案的情况下减少我们每次搜索的工作量。
具体代码如下:
只查找该数字之前:
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: listlen = len(nums) anw2 = -1 for anw1 in range(1,listlen): temp = nums[:anw1] if (target - nums[anw1]) in temp: anw2 = temp.index(target - nums[anw1]) break if anw2 != -1: return [anw2,anw1]
只查找该数字之后:
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: listlen = len(nums) anw2 = -1 for anw1 in range(0,listlen-1): temp = nums[anw1 + 1:] if (target - nums[anw1]) in temp: anw2 = temp.index(target - nums[anw1]) + anw1 + 1 break if anw2 != -1: return [anw1,anw2]
最好成绩:
执行用时: 28 ms
内存消耗: 15 MB
解法二:利用字典模拟hash表
hash查找在搜索方面有着巨大的优势,我们可以先利用字典构建一张hash表,再通过hash表查找:
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: hashmap = {} for numid,num in enumerate(nums): hashmap[num] = numid for i,num in enumerate(nums): j = hashmap.get(target - num) if j is not None and i!=j: return[i,j]
最好成绩:
执行用时: 40 ms
内存消耗: 15 MB
也可以一边查找,一边建表:
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: hashmap = {} for numid,num in enumerate(nums): need = target - num if need in hashmap: return[hashmap[need],numid] else: hashmap[num] = numid
最好成绩:
执行用时: 36 ms
内存消耗: 14.9 MB