【问题标题】:Problem in Linear search to solve a twoSum problem解决twoSum问题的线性搜索问题
【发布时间】:2019-03-20 09:32:13
【问题描述】:

我尝试了 Leecodes 中最简单的问题来解决 twoSum,

问题:

给定一个整数数组,返回两个数字的索引,使它们相加为特定目标。 您可以假设每个输入都恰好有一个解决方案,并且您不能两次使用 same 元素。

我的概念计划:固定第一个数字并找到(目标 - 第一个)
使用:O(n) 次迭代 * O(n) 线性搜索

from typing import List 
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in range(len(nums)):  #loop 
            find = target - nums[i]
            print(i, find)
            for j in range(i, len(nums)):#linear search 
                if find == nums[j]:
                    print(j)
                    return [i, j]
        return None 

当试图检查它时

In [51]: Solution().twoSum(nums, target)                                                                                      
0 3
0
Out[51]: [0, 0]

找不到问题,被leecode中最简单的问题卡住,郁闷。

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    尝试在第二个循环中从i + 1 循环到len(nums),因为您不能两次使用相同的元素。除此之外,它看起来是正确的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-31
      • 1970-01-01
      • 2021-05-29
      相关资源
      最近更新 更多