1.两个循环

class Solution:
    def twoSum(self, nums, target):
        n=len(nums)
        for i in range(n):
            for j in range(i+1,n):
                if (nums[j] == target - nums[i]):
                    return i,j
                    break
                else:
                    continue

 

编译通过但耗时太久

 

2.一个循环 直接看下相加是target数在不在列表中

class Solution:
    def twoSum(self, nums, target):
        n=len(nums)
        for i in range(n):
            a=target-nums[i]
            if (a in nums):
                j=nums.index(a)
                if(i==j):
                    continue
                else:
                    return i,j
                    break
            else:
                continue

 

3. 使用python字典 用时最少

class Solution:
    def twoSum(self, nums, target):
        d = {}
        for x in range(len(nums)): 
            if nums[x] in d:
                return d[nums[x]],x
            else:
                d[target - nums[x]] = x
                continue

 

相关文章:

  • 2021-05-23
  • 2021-07-06
  • 2021-09-14
  • 2021-08-15
  • 2021-04-23
  • 2021-07-30
  • 2021-12-25
  • 2021-05-12
猜你喜欢
  • 2022-12-23
  • 2021-12-03
  • 2021-11-07
  • 2021-12-20
  • 2021-10-29
  • 2022-12-23
相关资源
相似解决方案