python 求和_Python两次求和-蛮力法

我是Python的新手,刚刚开始尝试LeetCode来构建我的排骨.在这个经典问题上,我的代码错过了一个测试用例.

问题如下:

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].

我错过了目标编号为6的测试用例[3,2,4],它应该返回索引[1,2],但是在目标编号为6的测试用例[1,5,7]上击中了(当然哪个返回索引[0,1]),所以在while循环中似乎出了点问题,但是我不太确定是什么.

class Solution:

def twoSum(self, nums, target):

x = 0

y = len(nums) - 1

while x < y:

if nums[x] + nums[y] == target:

return (x, y)

if nums[x] + nums[y] < target:

x += 1

else:

y -= 1

self.x = x

self.y = y

self.array = array

return None

test_case = Solution()

array = [1, 5, 7]

print(test_case.twoSum(array, 6))

输出在目标为6的测试用例[3,2,4]上返回null,因此甚至没有汇总索引1和2,我可以为y分配错误吗?

解决方法:

有点不同的方法.我们将根据需要构建一个值字典,该字典由我们要查找的值构成键;如果我们寻找一个值,则在该值首次出现时会对其进行索引.一旦找到满足问题的值,就可以完成.这个时间也是O(N)

class Solution:

def twoSum(self, nums, target):

look_for = {}

for n,x in enumerate(nums):

try:

return look_for[x], n

except KeyError:

look_for.setdefault(target - x,n)

test_case = Solution()

array = [1, 5, 7]

array2 = [3,2,4]

given_nums=[2,7,11,15]

print(test_case.twoSum(array, 6))

print(test_case.twoSum(array2, 6))

print(test_case.twoSum(given_nums,9))

输出:

(0, 1)

(1, 2)

(0, 1)

标签:loops,arrays,python

来源: https://codeday.me/bug/20191024/1923681.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值