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时间

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