problem_solving_01.py 740 字节
Newer Older
1 2 3 4
"""
01.两数之和
"""

5 6
from typing import List

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
class Solution:

    def twoSum(self, nums: List[int], target: int) -> List[int]:
        """
        两数之和
        :param nums: 提供的数组
        :param target: 目标值
        :return: 返回值
        """
        hashmap = {}  # 字典不可以重复
        for index, num in enumerate(nums):  # enumerate迭代返回index和value
            hashmap[num] = index  # 解决value重复的问题

        print(hashmap)
        for i, num in enumerate(nums):
            j = hashmap.get(target - num)
            if j is not None and i != j:
                return [i, j]


if __name__ == '__main__':
    s = Solution()
    li = s.twoSum([2, 7, 11, 15], 9)
    print(li)