leetcode 1.兩數之和(python)

1.兩數之和

給定整數數組和目標值,返回和爲目標值的兩個整數的數組下標

假設每種輸入只有一個答案,但不能重複利用數組中的元素

例:

給定 nums = [2, 7, 11, 15], target = 9

因爲 nums[0] + nums[1] = 2 + 7 = 9

所以返回 [0, 1]

解1:暴力解

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        l=len(nums)
        for i in range(l-1):
            for j in range(i+1,l):
                if nums[i]+nums[j]==target:
                    return [i,j]
        return None

解2:字典

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dic=dict()
        for index,value in enumerate(nums):
            sub=target-value
            if sub in dic:
                return [index,dic[sub]]
            else:
                dic[value]=index #將數組存在以value爲鍵,以索引爲值的字典裏
        return None

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章