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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM