leecode day1 twosum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

my

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        res = []
        for i in range(len(nums)):
            for j in range(i, len(nums)):
                if i != j:
                    if nums[i] + nums[j] == target:
                        res.append(i)
                        res.append(j)
        return res

显示运行时间是4450~ms,击败8%左右,真的是小学生级别的代码。

reference

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dic = {}
        for i in range(len(nums)):
            n = nums[i]
            if n in dic:
                return [dic[n],i]
            dic[target-n] = i

        return [-1,-1]

上面这个冠军是20ms

具体问题具体分析,首先只有一个结果,可以不用遍历整个列表,只要找到答案就可以返回,其次,只有两个数字,可以用字典存一个序号,然后直接输出另一个,学习。

你可能感兴趣的:(leecode,leecode)