Two sum 两数之和

解法一:
用字典记录数组的值和下标。
第一遍遍历建立字典
第二遍遍历查找值

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        memo = {}
        for i in range(len(nums)):
            memo[nums[i]]=i
        for i in range(len(nums)):
            delta = target-nums[i]
            if delta in memo:
                if i!=memo[delta]:
                    return i,memo[delta]

解法二:
一边查找一边建立字典。
遍历一遍

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        memo = {}
        for i in range(len(nums)):
            delta = target-nums[i]
            if delta in memo and memo[delta]!=i:
                return i,memo[delta]
            memo[nums[i]]=i

你可能感兴趣的:(Two sum 两数之和)