Lootcode 1. Two Sum The Solution of Python and Javas

来源:互联网 发布:打破刚性兑付 知乎 编辑:程序博客网 时间:2024/06/08 09:56

Description:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Python:

class Solution(object):    def twoSum(self, nums, target):        """        :type nums: List[int]        :type target: int        :rtype: List[int]        """        table={}#创建字典        for index,n in enumerate(nums):#List中每一个元素的索引和值            a=target-n#计算当前值与target的差值            if a in table:#判断差值是否在字典中                return [table[a],index]#如果在,说明有前面的n值(差值)和现在的n值之和等于target,返回存有差值的table值            table[n]=index#如果不在,将当前索引存入字典{table[n]:index}

思路是创建一个字典,存入nums中每个值,值为key,索引为value,判断target与当前值的差值是否为已存入字典的值,如果有,则输出这两个值的索引。时间复杂度O(n)

Javascript:

/** * @param {number[]} nums * @param {number} target * @return {number[]} */var twoSum = function(nums, target) {    let table={},a;/    for(let index=0;index<nums.length;index++) {        a=target-nums[index];        if(a in table) {            return [table[a],index];        }        table[nums[index]]=index;    }};

思路基本一致

0 0
原创粉丝点击