LeetCode: Two Sum

Solution 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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, end

Solution 2

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
0%