LeetCode1:两数之和
程序员文章站
2024-03-09 11:51:35
...
目录
一、题目
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
二、示例
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
三、思路
1、暴力法:双重for循环,遍历每个元素 x,并查找是否存在一个值与 target - x 相等的目标元素。
所以执行时间比较长:
2、该方法是上一个方法的优化。关键是找到target - x,若存在,则查找target - x的索引,并且与x的索引不相等。
执行通过,且时间比上一个方法少很多。
3、用字典求解。字典dict存储每一个数值,key为下标,value为nums数值。
通过字典的方法,查找效率快很多,执行速度大幅缩短!
四、代码
1、
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
res = []
for i in range(len(nums) - 1):
for j in range(i + 1, len(nums)):
if target - nums[i] == nums[j]:
res.append(i)
res.append(j)
return res
if __name__ == '__main__':
nums = [2, 7, 11, 15]
target = 9
s = Solution()
ans = s.twoSum(nums, target)
print(ans)
2、
class Solution:
def twoSum(self, nums, target):
for i in range(len(nums)):
if (target - nums[i] in nums and i != nums.index(target - nums[i])):
return [i, nums.index(target - nums[i])]
if __name__ == '__main__':
nums = [2, 7, 11, 15]
target = 9
s = Solution()
ans = s.twoSum(nums, target)
print(ans)
3、(1)
class Solution:
def twoSum(self, nums, target):
dict = {}
for i, num in enumerate(nums):
dict[num] = i
for i, num in enumerate(nums):
j = dict.get(target - num)
if j != i and j is not None:
return [i, j]
if __name__ == '__main__':
nums = [2, 7, 11, 15]
target = 9
s = Solution()
ans = s.twoSum(nums, target)
print(ans)
3、(2)
class Solution:
def twoSum(self, nums, target):
dict = {}
for i, num in enumerate(nums):
if dict.get(num) is None:
dict[num] = i
if dict.get(target - num) is not None and dict.get(target - num) != i:
return [dict.get(target - num), i]
if __name__ == '__main__':
nums = [2, 7, 11, 15]
target = 9
s = Solution()
ans = s.twoSum(nums, target)
print(ans)
3、(3)
class Solution:
def twoSum(self, nums, target):
dict = {}
for i, num in enumerate(nums):
if dict.get(target - num) is not None:
return [i, dict.get(target - num)]
dict[num] = i
if __name__ == '__main__':
nums = [2, 7, 11, 15]
target = 9
s = Solution()
ans = s.twoSum(nums, target)
print(ans)
上一篇: leetcode1