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 traversing the list using enumerate() to record the idx and elem, then
traversing 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 whether 
elem which substracts from the target is in the list.It will more efficient.
	On 01.28, I thought it's possible to use two pointers to solve this problem. First, Sort the list in 
ascending, then we can use i, j to travserse list from head & tail respectively.

My code:

# mapping the subtract num in list
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

# pointers
def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        new_nums = sorted(nums, reverse=False)
        i = 0
        j = len(new_nums) - 1
        while i < j:
            x = new_nums[i]
            y = new_nums[j]
            total = x + y
            if total == target:
                if x != y:
                    return [nums.index(x), nums.index(y)]
                elif x == y:
                    return [i for (i, m) in enumerate(nums) if m==x]
            elif total < target:
                i += 1
            elif total > target:
                j -= 1
        return False

Execution takes:24ms
Memory consumption:13.1MB

The others code:

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

Execution time takes:20ms
Memory consumption:13.1MB

Execution time for searching key in dict:

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

summary

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

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值