LeetCode-两数之和(python)

1.暴力求解:时间复杂度O(n^{2})空间复杂度O(1)

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(0,len(nums)-1):
            for j in range(i+1,len(nums)):
                if nums[i]+nums[j]==target:
                    return [i,j]

2.两遍hash表:时间复杂度O(n)空间复杂度O(n)

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dic={}
        for i,num in enumerate(nums):
            dic[num]=i
        for i,num in enumerate(nums):
            j=dic.get(target-num) 
            if j is not None and  j!=i:
                return [i,j]

 

你可能感兴趣的:(LeetCode-两数之和(python))