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)
上一篇:JavaScript-Map()增量值


下一篇:javascript-setTimeout for循环(1次超时,然后一次循环)(双循环)