LeetCode: Two Sum
Solution #1
from typing import List
def twoSum(nums: List[int], target: int) -> List[int]:
"""
Finds two numbers in a list that sum up to the target value.
Args:
nums (List[int]): A list of integers.
target (int): The target value.
Returns:
List[int]: A list containing the indices of the two numbers that sum up to the target.
Examples:
>>> nums = [2, 7, 11, 15]
>>> target = 9
>>> result = twoSum(nums, target)
>>> print(result)
[0, 1]
"""
max_index = len(nums) - 1
start, end = 0, 1
while start != end:
if nums[start] + nums[end] == target:
break
# Setting up next iteration
if end < max_index:
end += 1
elif start < max_index:
start += 1
end = start + 1
return start, endSolution #2
from typing import List
def twoSum(nums: List[int], target: int) -> List[int]:
"""
Finds two numbers in a list that sum up to the target value.
Args:
nums (List[int]): A list of integers.
target (int): The target value.
Returns:
List[int]: A list containing the indices of the two numbers that sum up to the target.
Examples:
>>> nums = [2, 7, 11, 15]
>>> target = 9
>>> result = twoSum(nums, target)
>>> print(result)
[0, 1]
"""
summands = {}
for i, number in enumerate(nums):
if number in summands:
break
summands[target - number] = i
return summands[number], i