算法練習每日一題:兩數之和

1. 兩數之和

給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。

你可以假設每種輸入只會對應一個答案。但是,你不能重複利用這個數組中同樣的元素。

示例:

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

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

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/two-sum

# 枚舉解法
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        length = len(nums)
        if length < 2:
            return None
        for i in range(0, length):
            for j in range(i,length):
                if nums[i] + nums[j] == target and i != j:
                    return [i ,j]
                else:
                    continue
        return None
"""
# 藉助於 hash 表結構,{value:index}一次遍歷
# Testcase:

>>> Solution().twoSum([2,7,11,15],9)
[0,1]

>>> Solution().twoSum([3,3],6)
[0,1]

"""

class Solution:
    def twoSum(self, nums, target):
        length = len(nums)
        if length < 2:
            return None
        rst = {}
        temp = 0
        for i in range(0, length):
            temp = target - nums[i]
            if rst.get(temp) != None and rst.get(temp) != i:
                return [rst.get(temp),i]
            rst[nums[i]] = i
        return None

    if __name__ == "__main__":
        import doctest
        doctest.testmod(verbose=True)

題解:

  1. 首先根據題意,使用枚舉法來模擬求解,需要注意題幹中不是相同的元素,指的應該是非相同位置的元素
  2. 使用空間換效率,藉助於 hash 表 key - value 格式存貯列表的元素和對應的位置,主要是 hash 的查找效率的O(1);
    這時需要注意 2 點:返回結果的 list 的元素順序,已存在 hash 表的 value 應該在前;題幹中非相同元素的要求和 hash 非重複 key 的特性,應該先進行查找後進行存儲,避免元素被替換。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章