python版Leetcode刷題:兩數之和

 整了個idea的leetcode插件,方便刷題,記錄下刷的第一題!

三種方法中最後一個是最開始想出來的,後來修改nums之後發現不能返回,就有了1和2兩種方法!

題目中有說明:假設每種輸入只會 對應一個答案。

有想法的朋友可以自己實現一下。

# 給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。 
# 
#  你可以假設每種輸入只會對應一個答案。但是,數組中同一個元素不能使用兩遍。 
# 
#  可以給定任意數組,並且返回下標列表
# 
#  示例: 
# 
#  給定 nums = [2, 7, 11, 15], target = 9
# 
# 因爲 nums[0] + nums[1] = 2 + 7 = 9
# 所以返回 [0, 1]
#  
#  Related Topics 數組 哈希表

# python3解法,思路大致相同
# leetcode submit region begin(Prohibit modification and deletion)
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dict = {}
        iList = []
        for index, num in enumerate(nums):
            dict[num] = index
        for i, num in enumerate(nums):
            j = dict.get(target - num)
            if j is not None and i != j:
                iList.append(i)
                iList.append(j)
        return list(set(iList))

    def Sum2(self, nums, target):
        dict = {}
        res = []
        for index, num in enumerate(nums):
            dict[num] = index
        for i, num in enumerate(nums):
            j = dict.get(target - num)
            if j is not None and i != j:
                res.append((i, j))
                del dict[target - num]
                del dict[num]
        return res

    def twosum(self, nums, target):
        # 初始化一個字典,用於記錄(值:索引)
        dict = {}
        # 遍歷enumerate(a),
        # enumerate() 函數用於將一個可遍歷的數據對象(如列表、
        # 元組或字符串)組合爲一個索引序列,
        # 同時列出數據和數據下標。
        for i, num in enumerate(nums):
            # 如果目標值(target)減去num在字典dict中
            if target - num in dict:
                # 返回結果(target - num)以及結果的索引(i)
                return [dict[target - num], i]
            else:
                # 將num以及索引值添加到dict中
                dict[num] = i


if __name__ == '__main__':
    nums = [2, 7, 11, 15, 4, 5, 3, 6, 1, 8]
    target = 9
    resl = Solution()
    print("第一種方法--twoSum結果是:",  resl.twoSum(nums, target))
    print("第二種方法--Sum2結果是:", resl.Sum2(nums, target))
    print("第三種方法--twosum結果是:", resl.twosum(nums, target))

結果如下:

D:\anaconda\python.exe D:/software/idea/dataTemp/leetcode/editor/cn/[1]兩數之和.py
第一種方法--twoSum結果是: [0, 1, 4, 5, 6, 7, 8, 9]
第二種方法--Sum2結果是: [(0, 1), (4, 5), (6, 7), (8, 9)]
第三種方法--twosum結果是: [0, 1]

 

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