其他分享
首页 > 其他分享> > Leetcode | Two Sum

Leetcode | Two Sum

作者:互联网

Description:

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.

Example:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

Ideas:

The first idea in my mind is that traverse the list using enumerate() to record the idx and elem, then traverse the remaining elem in the list again, and add the two elem to judge if the result is equal to the target. In this way, i found it does work, but it’s too slow.
Then i saw that if i can judge elem which is substract by the target and first elem in the list.It will more efficient.

My code:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i1, x in enumerate(nums):
            temp = target-x
            if (temp in nums) and (nums.index(temp)!=i1):
                i2 = nums.index(temp)
                return [i1, i2]

Execution takes:20ms
Memory consumption:12.9MB

The others code:

def twoSum(nums, target):
    """use dict"""
    dct = {}
    for i, n in enumerate(nums):
        cp = target - n
        if cp in dct:
            return [dct[cp], i]
        else:
            dct[n] = i

key in dict : 1.088 s
dict.get(key) : 1.294 s
dict[key] : 1.01 s

summary

It seems that I haven’t consider time complexity, maybe i have forgotten what is time complexity.

In this series,I’ll record my exercise in leetcode, and try to write the process in English. This’s the first essay in 2021.01.27 by Cheung. Hope it will be a good start.

标签:return,target,nums,Sum,Two,elem,dict,dct,Leetcode
来源: https://blog.csdn.net/shawnchang777/article/details/113245769