Leetcode Two Sum [easy] (Python)

Description

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Solution1

1
2
3
4
5
6
7
8
9
10
11
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums) - 1):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]

Intuitive ideas, violent solutions, two cycles. low efficiency.

Solution2

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
keys = {}
for i in range(len(nums)):
if target - nums[i] in keys:
return [keys[target - nums[i]], i]
if nums[i] not in keys:
keys[nums[i]] = i

Solution3

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
collected = {}
for idx,val in enumerate(nums):
diff = target - val
if diff in collected:
return [collected[diff], idx]
collected[val] = idx

Tips

enumerate()

description

The enumerate() function is used to combine a traversable data object (such as a list, tuple, or string) into an index sequence, listing both data and data subscripts, typically used in a for loop.

grammar

以下是 enumerate() 方法的语法:

enumerate(sequence, [start=0])

parameter

  • Sequence – A sequence, iterator, or other support iterative object.
  • Start – the starting position of the subscript.

return value

Returns the enumerate object.

-------------End of the articleThank you for reading-------------
  • Author of this article:zfish
  • Link to this article: archives/bc60cdc1.html
  • Copyright Notice: All articles in this blog, except for special statements, please indicate the source!
0%