给定一个整数数列,找出其中和为特定值的那两个数。

你可以假设每个输入都只会有一种答案,同样的元素不能被重用。

示例:

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

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

我的代码:(时间复杂度为n2),两个循环判断当前值与列表之后的值是否相等。
def twoSum(self,nums, target):
        index=0
        while index<len(nums):      
            i=index+1
            while i<len(nums):
                temp=target-nums[index]
                if temp==nums[i]:
                    return [index,i]
                else:
                    i+=1
            index+=1

 别人的代码:(时间复杂度为n)   用字典的key,value来存储两个值,其中key用来存储nums的值,value用来存储nums的索引。

def twoSum(nums,target):
    dic={}
    for i,j in enumerate(nums):
        if target-j in dic:
           return [dic[target-j],i]
        else:
            dic[j]=i

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-11-25
  • 2021-11-21
  • 2022-02-09
  • 2022-02-22
猜你喜欢
  • 2022-02-21
  • 2022-12-23
  • 2021-05-25
  • 2022-03-07
  • 2022-12-23
  • 2021-10-26
  • 2022-12-23
相关资源
相似解决方案