【LeetCode】1.Two Sum 兩數之和(Python)

1. 題目

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

注意題目中返回的是數組下標

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """

2. 解答

最容易想到的是暴力解法,顯然可行但沒必要。

2.1 錯誤解答(自己的)

  1. 首先,題目要求返回下標,因此應保存數的對應下標,Python中使用字典進行保存下標這一操作。字典形式爲“數:下標”
  2. 其次,想到可以通過對數組排序後,設置首尾指針,若首尾指針和大於target,則尾指針左移;若和小於target,則首指針右移;若和等於target,則找到對應兩數,在字典中找到對應下標,返回結果。思路轉代碼,內心竊喜
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if len(nums) < 2:
            return None
        d = {}
        for i in xrange(len(nums)):
            d[nums[i]] = i
        nums.sort()
        left = 0
        right = len(nums) - 1
        two = nums[left] + nums[right]
        while left < right and two != target:
            if two < target:
                left += 1
            else:
                right -= 1
            two = nums[left] + nums[right] 
        return [d[nums[left]], d[nums[right]]]
  1. 運行出錯,當nums=[3,3]時,按照上述代碼返回是[1,1]。忽略了數組中存在相同元素的情況

2.2 正確解答(別人的)

以下思路爲根據別人的正確代碼複述思路。至於別人是誰,我也不知道,LeetCode上的

  1. 首先,題目要求返回數組下標,因此應保存數的對應下標,Python中使用字典進行保存下標這一操作。字典形式爲“數:下標”(我的這條思路是正確的 竊喜√)
  2. 依次遍歷數組,若“target-當前數”在字典中,則找到對應兩數,返回當前下標,以及在字典中找到“target-當前數”對應的下標;若“target-當前數”不在字典中,則在字典中保存“當前數:當前數的下標”。
class Solution(object):
   def twoSum(self, nums, target):
       """
       :type nums: List[int]
       :type target: int
       :rtype: List[int]
       """
       d = {}
       for i in xrange(len(nums)):
           other = target - nums[i]
           if other in d:
               left = d[other]
               right = i
               return [left, right]
           d[nums[i]] = i
       return None

2.3 對比

不要想複雜了,其實挺容易的,離正確只差一丟丟,這一丟丟就是菜鳥與大佬的差距8
博文爲記錄用,歡迎留言交流。

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