mirror of
https://hub.njuu.cf/TheAlgorithms/Python.git
synced 2023-10-11 13:06:12 +08:00
Add Python type hints and doctests to other/two_sum.py (#2467)
* Add Python type hints and doctests to other/two_sum.py #2465 * Update other/two_sum.py Co-authored-by: Christian Clauss <cclauss@me.com> * Update other/two_sum.py Co-authored-by: Christian Clauss <cclauss@me.com> * Update two_sum.py Co-authored-by: Christian Clauss <cclauss@me.com>
This commit is contained in:
parent
9200a2e543
commit
5f9be0a613
@ -11,21 +11,37 @@ Given nums = [2, 7, 11, 15], target = 9,
|
|||||||
Because nums[0] + nums[1] = 2 + 7 = 9,
|
Because nums[0] + nums[1] = 2 + 7 = 9,
|
||||||
return [0, 1].
|
return [0, 1].
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
def twoSum(nums, target):
|
def two_sum(nums: list[int], target: int) -> list[int]:
|
||||||
"""
|
"""
|
||||||
:type nums: List[int]
|
>>> two_sum([2, 7, 11, 15], 9)
|
||||||
:type target: int
|
[0, 1]
|
||||||
:rtype: List[int]
|
>>> two_sum([15, 2, 11, 7], 13)
|
||||||
|
[1, 2]
|
||||||
|
>>> two_sum([2, 7, 11, 15], 17)
|
||||||
|
[0, 3]
|
||||||
|
>>> two_sum([7, 15, 11, 2], 18)
|
||||||
|
[0, 2]
|
||||||
|
>>> two_sum([2, 7, 11, 15], 26)
|
||||||
|
[2, 3]
|
||||||
|
>>> two_sum([2, 7, 11, 15], 8)
|
||||||
|
[]
|
||||||
|
>>> two_sum([3 * i for i in range(10)], 19)
|
||||||
|
[]
|
||||||
"""
|
"""
|
||||||
chk_map = {}
|
chk_map = {}
|
||||||
for index, val in enumerate(nums):
|
for index, val in enumerate(nums):
|
||||||
compl = target - val
|
compl = target - val
|
||||||
if compl in chk_map:
|
if compl in chk_map:
|
||||||
indices = [chk_map[compl], index]
|
return [chk_map[compl], index]
|
||||||
print(indices)
|
chk_map[val] = index
|
||||||
return [indices]
|
return []
|
||||||
else:
|
|
||||||
chk_map[val] = index
|
|
||||||
return False
|
if __name__ == "__main__":
|
||||||
|
import doctest
|
||||||
|
|
||||||
|
doctest.testmod()
|
||||||
|
print(f"{two_sum([2, 7, 11, 15], 9) = }")
|
||||||
|
Loading…
Reference in New Issue
Block a user