LeetCode 第一题:两数之和--python

与C++想法一样,个人实现的是最简单的for循环:
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        towSum=[]
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                if(nums[i]+nums[j]==target):
                       towSum.append(i)
                       towSum.append(j)
        return towSum

以下优化转自( wx公众号:小詹学python [先注明:不是博主的公众号]):
1.将上述双循环可以优化一下为单循环:
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        towSum=[]
        for i in range(len(nums)):
            onenum=nums[i]
            twonum=target-nums[i]
            if twonum in nums:
                j=nums.index(twonum)
                if i!=j:
                       towSum.append(i)
                       towSum.append(j)
        return towSum

上述两种方法循环时间都很长:
按照官方代码来说,还是采用字典更好:

2.字典优化:
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        #创建字典一:存入nums[i],i
        num_dict={num[i]: i fori in range(len(nums))}
        #创建字典二:存入i:target-nums[i]
        num_dict2={i:target-num[i] fori in range(len(nums))}

        towSum=[]
        for i in range(len(nums)):
            j=num_dict.get(num_dict2.get(i))
            if (j is not None) and (j!=i):
                towSum=[i,j]
                break
        return towSum

你可能感兴趣的:(代码练习,LeetCode-python)