leetcode 之路-两数之和

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

解法:

class Solution:
    def twoSum(self, nums, target):

        """
        #暴力算法
        for i in range(len(nums)):
            for j in range(i, len(nums)):
                if nums[i] +  nums[j] == target and i != j:
                    return [i, j]
        """
        hashed = {}
        for i in range(len(nums)):

            if target - nums[i] in hashed:
                return [hashed[target - nums[i]], i]
            else:
                hashed[nums[i]] = i

第二种算法:


利用空间换时间,将num[i](作为键), 以及索引(作为值)存放在字典中,如果当taget-num[i](作为键) 在字典中时,说明此时num[i] + 字典中的某一个键 = target,则某一个键对应的值,以及此时的i,即为所要返回的

猜你喜欢

转载自blog.csdn.net/jiayangwu/article/details/80489273