leetcode No1 兩數之和

給定一個整數數組和一個目標值,找出數組中和爲目標值的兩個數。

你可以假設每個輸入只對應一種答案,且同樣的元素不能被重複利用。

示例:

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

因爲 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

 

 

一開始遇到這個題目的想法就是笨方法:遍歷,一個一個加唄。

反正c++ 忘得差不多了,上個python代碼

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                if nums[i] + nums[j] == target:
                    return i,j

這個方法我覺得好low啊,for越多越冗長。

算了,就這樣吧,網上方法大同小異

今天我發現一個這個函數,enumerate

例子如下

>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))       # 小標從 1 開始
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

以前就看到過,第一次正式使用

修改後的代碼:

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dic = {}
        for index,num in enumerate(nums):
            
            if num in dic:
                return(dic[num],index)
            else:
                dic[target - num] = index
        

這個代碼牛逼在用了字典和enumerate(枚舉)

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