Leetcode 1 - python 3

1 Two Sum

刚开始接触python 对于函数的了解还不多

如果暴力循环会提示超时 时间复杂度是O(n*n)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        i = 0
        while i < len(nums):
            if i == len(nums) - 1:
                return "No solutions"
            else:
                j = i + 1
                while j < len(nums):
                    if nums[i] + nums[j] == target:
                        return [i, j]
                    else:
                        j = j + 1
            i = i + 1

所以要寻求其他办法

enumerate 枚举

        dict = {}
        for i, num in enumerate(nums):
            if num in dict:
                return [dict[num], i] # dic[num] equals to i1, i = i2 -> [i1, i2]
            else: # if num not exist in dic
                dict[target - num] = i # add it in the dict

你可能感兴趣的:(Y)