Here‘s no Duke anymore

minty_Brit666

Today’s blog is about the practice of the leetcode.
And I’ll give my own answer in this blog.

  1. The sum of two numbers
    **Given an integer array nums and an integer target value target, find the two integers in the array and the target value target and return their array subscripts.
    You can assume that there is only one answer for each type of input. However, the same element in the array cannot be repeated in the answer.
    You can return the answers in any order.

Source: LeetCode
Link: https://leetcode-cn.com/problems/two-sum
Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.

**
we can use the for loop twice to iterate through all the values and find the two numbers that sum to the target values:
Screen Shot 1

def twoSum(self, nums, target):
    n=len(nums)
    for idx in range(n):
        for jdx in range(idx+1,n):
            if nums[idx] + nums[jdx] == target:
                return idx,jdx

Or we can use the index to reduce a loop:
Screen Shot 2

def twoSum(self, nums, target):
    for idx in range(len(nums)):
        if target - nums[idx] in nums:
            if idx != nums.index(target - nums[idx]):
                return idx,nums.index(target - nums[idx])

The easiest way to do that is to use a hash dictionary:
Screen Shot 3

def twoSum(self, nums, target):
    dict = {}
    for idx in range(len(nums)):
        x = target - nums[idx]
        if x in dict:
            return dict[x],idx
        else:
            dict[nums[idx]] = idx

Of the three methods above, the last one consumes the least amount of system resources and takes the least amount of time.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值