leetcode_1-two-sum

給定一個整數數列,找出其中和爲特定值的那兩個數。

你可以假設每個輸入都只會有一種答案,同樣的元素不能被重用。

示例:

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

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

 

第一次:

def twoSum( nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: List[int]
    """
    result = []
    for index, i in enumerate(nums[:-1]):
        other = target - i
        if other in nums[index+1:] :
            next_index = nums[index+1:].index(other) + (index+1)
            if index > next_index:
                result.append(next_index)
                result.append(index)
            elif next_index > index:
                result.append(index)
                result.append(next_index)
            break
    return result
顯示總運行時間1148ms,顯示值超過了30%的Python3程序,繼續優化。

list切片是o(k)的時間複雜度,換個dict試試

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

             map[num] = i

結果立馬到50ms時間

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