leetCode

发布时间:2019-10-11 09:02:40编辑:auto阅读(2912)

    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);

关键字