leetCode

two sum

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].

result:

//typescript
var twoSum=function(nums:Array<number>,target:number):Array<number>{
    let len=nums.length;
    let obj={};
    for(let i=0;i<len;i++){
        if(obj[target-nums[i]]!==undefined){
            return [obj[target-nums[i]],i];
        }
        obj[nums[i]]=i;//翻转 key value
    }
}
//python3
def twoSum(nums,target):
    dict={};
    for i in range(len(nums)):
        if target-nums[i] in dict:
            return dict[target-nums[i]],i;
        dict[nums[i]]=i;
        
result=twoSum([1,2,3,-1],0);
print(result);
    原文作者:lx_blog
    原文地址: https://segmentfault.com/a/1190000010560838
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞