python代码-leetcode1 两数相加

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

 

posted @ 2018-07-31 10:45  扣子老三  阅读(1844)  评论(0编辑  收藏  举报