【问题标题】:Python Two Sum - Brute Force ApproachPython 二和 - 蛮力方法
【发布时间】:2019-05-29 16:37:54
【问题描述】:

我是 Python 新手,刚刚开始尝试 LeetCode 来建立自己的能力。在这个经典问题上,我的代码遗漏了一个测试用例。

问题如下:

给定一个整数数组,返回两个数字的索引,使它们相加到一个特定的目标。

您可以假设每个输入都只有一个解决方案,并且您不能两次使用相同的元素。

例子:

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

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

我错过了目标编号为 6 的测试用例 [3,2,4],它应该返回 [1,2] 的索引,但命中了目标编号为 [1,5,7] 的测试用例6 个(当然返回索引 [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 错误?

【问题讨论】:

  • 您的解决方案仅适用于排序列表。
  • 另外,请确保 x 和 y 不相等。

标签: python arrays loops


【解决方案1】:

蛮力解决方案是在列表上双重嵌套一个循环,其中内部循环仅查看大于外部循环当前所在的索引。

class Solution:
    def twoSum(self, nums, target):
        for i, a in enumerate(nums, start=0):
            for j, b in enumerate(nums[i+1:], start=0):
                if a+b==target:
                    return [i, j+i+1]

test_case = Solution()
array = [3, 2, 4]
print(test_case.twoSum(array, 6))

array = [1, 5, 7]
print(test_case.twoSum(array, 6))

array = [2, 7, 11, 15]
print(test_case.twoSum(array, 9))

输出:

[1, 2]
[0, 1]
[0, 1]

【讨论】:

  • 您的解决方案非常干净。我需要帮助了解通过添加 j+i+1 发生的登录。为什么是三个而不是 i+1?我很好奇
【解决方案2】:

有点不同的方法。我们将根据需要构建一个值字典,该字典由我们正在查找的值作为键。如果我们查找一个值,我们会在该值第一次出现时跟踪该值的索引。一旦找到满足问题的值,您就完成了。这个时间也是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)

【讨论】:

  • 我明白了,我觉得我应该从使用枚举开始。启动更简单、更高效。
  • 这始终是一个学习过程,但我们不想在不需要的时候重新发明轮子:P。很高兴能提供帮助。
【解决方案3】:
class Solution:
    def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            ls=[]
            l2=[]
            for i in nums:
                ls.append(target-i)

            for i in range(len(ls)):
                if ls[i] in nums  :
                    if i!= nums.index(ls[i]):
                        l2.append([i,nums.index(ls[i])])            
            return l2[0]


x= Solution()
x.twoSum([-1,-2,-3,-4,-5],-8)

输出

[2, 4]

【讨论】:

    【解决方案4】:
    import itertools
    
    class Solution:
        def twoSum(self, nums, target):
            subsets = []
            for L in range(0, len(nums)+1):
                for subset in itertools.combinations(nums, L):
                    if len(subset)!=0:
                        subsets.append(subset)
            print(subsets) #returns all the posible combinations as tuples, note not permutations!
            #sums all the tuples
            sums = [sum(tup) for tup in subsets]
            indexes = []
            #Checks sum of all the posible combinations
            if target in sums:
                i = sums.index(target)
                matching_combination = subsets[i] #gets the option
                for number in matching_combination:
                    indexes.append(nums.index(number))
                return indexes
            else:
                return None
    
    
    test_case = Solution()    
    array = [1,2,3]
    print(test_case.twoSum(array, 4))
    

    我正在尝试您的示例以供自己学习。我对我的发现感到满意。我使用itertools 为我制作了所有数字组合。然后我使用列表操作对输入数组中所有可能的数字组合求和,然后我只需检查目标是否在 sum 数组内。如果不是,则返回 None,否则返回索引。请注意,如果这三个索引加起来等于目标,则此方法也将返回所有三个索引。抱歉拖了这么久:)

    【讨论】:

      【解决方案5】:

      即使代码行更短,这个也是更全面、内聚高效的一个。

      nums = [6, 7, 11, 15, 3, 6, 5, 3,99,5,4,7,2]
      target = 27
      n = 0
      
      for i in range(len(nums)):
          
          n+=1
          if n == len(nums):
            n == len(nums)
            
          else:
              if nums[i]+nums[n] == target:
                # to find the target position 
                print([nums.index(nums[i]),nums.index(nums[n])])
                # to get the actual numbers to add print([nums[i],nums[n]])
      

      【讨论】:

      • 我认为这现在可能适用于所有测试用例,a=[3,3] t=6, a[9,9] t=18
      猜你喜欢
      • 1970-01-01
      • 2020-02-16
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      • 2015-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多