LeetCode Two Sum 解题思路(python)
问题描述
给定一个整数数组, 返回两个数字的索引, 使两个数字相加为到特定值。
您可以假设每个输入都有一个解决方案, 并且您不能使用相同的元素两次。
方法 1: 蛮力
蛮力方法很简单。循环遍历每个元素 xx 并查找是否有另一个值等于目标 xtarget−x。
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(0,len(nums)):
            for j in range (i+1,len(nums)):
                if nums[i] + nums[j] == target:
                    return [i,j]
方法2: 哈希表
为了提高运行时速度, 我们需要一种更有效的方法来在数组中查找变量。维护数组中每个元素的映射到其索引的最佳方法是什么?哈希表。
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        hashDict = {}
        for i in range(len(nums)):
            x = nums[i]
            if target-x in hashDict:
                return (hashDict[target-x], i)
            hashDict[x] = i
此方法,在速度排行打败57%的方案
参考
https://stackoverflow.com/questions/30021060/two-sum-on-leetcode
posted on 2018-10-13 13:38 lion_zheng 阅读(279) 评论(0) 收藏 举报
 
                    
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号