Leetcode——1.两数之和(python)

88 篇文章 3 订阅

1.两数之和

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路:

这个题看起来简单,但是需要注意一些方面:

1. 找到符合条件的两个数,返回的是一个列表,列表里是这两个数对应的下标。

2. 注意不能是自己加自己。

程序代码1:

直接用两个for循环暴力破解。

class Solution:
    def twoSum(self, nums, target):
        nums_length = len(nums)
        for i in range(nums_length):
            for j in range(nums_length):
                if i != j:
                    if nums[i] + nums[j] == target:
                        return [i,j]

nums = [2, 7, 11, 15]
target = 9
s = Solution()
print(s.twoSum(nums, target))

但是很容易发现两个for循环进行运算的话,其中进行了很多重复的计算,比如2+7,7+2,2+11,11+2 .... 所以要解决不必要的重复计算。

程序代码2:

同样也是两个for循环,遍历每一个列表元素,查找看是否存在与target - nums[i] 相同的目标元素。这里把重复的计算去掉,来提高运行速度。

class Solution:
    def twoSum(self, nums, target):
        nums_length = len(nums)
        for i in range(0,nums_length):
            num = target - nums[i]
            for j in range(i+1,nums_length):
                if num == nums[j]:
                    return [i,j]

nums = [2, 7, 11, 15]
target = 9
s = Solution()
print(s.twoSum(nums, target))

程序代码3:

进行优化,用一次for循环来实现。

class Solution:
    def twoSum(self, nums, target):
        nums_length = len(nums)
        for i in range(nums_length):
            one_num = nums[i]
            the_other_num = target - one_num
            if the_other_num in nums:
                j = nums.index(the_other_num)
                if i != j:
                    return [i,j]

nums = [2, 7, 11, 15]
target = 9
s = Solution()
print(s.twoSum(nums, target))

程序代码4:

对上面一个for循环再进行优化,这里模拟哈希表进行运算。

class Solution:
    def twoSum(self, nums, target):
        nums_length = len(nums)
        hashmap = {nums[i]: i for  i in range(nums_length)}
        for i in range(nums_length):
            one_num = nums[i]
            the_other_num = target - one_num
            if the_other_num in hashmap and i != hashmap[the_other_num]:
                    return [i,hashmap[the_other_num]]

nums = [2, 7, 11, 15]
target = 9
s = Solution()
print(s.twoSum(nums, target))

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

suxiaorui

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值