[Leetcode] two sum (python, javascript)

728x90
반응형

합한 수가 target이면 현재 수 x와 target-x의 위치를 찾으면 된다 

각 숫자의 위치를 저장해가면서 이미 지나간 위치에서 target-x가 있다면 [현재위치, dict[target-x]] 를 리턴하면 된다.

 

1. python

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dict={}
        for i,x in enumerate(nums):
            if target-x in dict:
                return [dict[target-x],i]
            dict[x]=i

 

2. javascript

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

 

728x90
반응형
TAGS.

Comments