leetcode 1

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

知识点:

  1.时间复杂度,空间复杂度.     参考: https://zhuanlan.zhihu.com/p/50479555

  2.哈希表.                               参考: https://zhuanlan.zhihu.com/p/95156642

下面是我参考别人解题思路做的.

 1 class Solution:
 2     def twoSum(self, nums: List[int], target: int) -> List[int]:
 3         list = []
 4         for k in range(len(nums)):
 5             m=target- nums[k]
 6             if m in list:
 7                 return (list.index(m),k)
 8             else:
 9                 list.append(nums[k])
10                 k+=1

下面是跑的最快的Python3 代码  24ms

1 class Solution:
2     def twoSum(self, nums: List[int], target: int) -> List[int]:
3         n=len(nums)
4         hashmap={}
5         for i in range(n):
6             if nums[i] in hashmap:
7                 return[i,hashmap[nums[i]]]
8             else:
9                 hashmap[target-nums[i]]=i

Python3 代码  28ms

1     def twoSum(self, nums: List[int], target: int) -> List[int]:
2       
3         hashtable = dict()
4         for i, num in enumerate(nums):
5             if target - num in hashtable:
6                 return [hashtable[target - num], i]
7             hashtable[nums[i]] = i
8         return []

 

原文地址:https://www.cnblogs.com/hello1123/p/14975786.html