美文网首页
LeetCode(1-两数之和)(Python)

LeetCode(1-两数之和)(Python)

作者: TinyShu | 来源:发表于2018-09-05 16:32 被阅读0次
image.png
解法一(7280 ms):
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        L = []
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                if nums[i] + nums[j] == target:
                    L.append(i)
                    L.append(j)
                    return L  
解法二(896 ms ):
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            if target-nums[i] in nums:
                idx=nums.index(target-nums[i])
                if idx!=i:
                    return [i,idx]
解法三(36ms):
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dic={}
        for i in range(len(nums)):
            var=target-nums[i]
            if nums[i] in dic:
                return [dic[nums[i]],i]
            else:
                dic[var] = i

相关文章

网友评论

      本文标题:LeetCode(1-两数之和)(Python)

      本文链接:https://www.haomeiwen.com/subject/lmwawftx.html