Leetcode- Two Sum

eaasurmind·2022년 4월 27일
0

코딩테스트

목록 보기
1/1

problem

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

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

You can return the answer in any order.

var twoSum = function(nums, target) {
   const map = new Map();
    for(let i=0; i<nums.length; i++) {
        map.set(nums[i], i)
    }
    for(let i =0; i<nums.length; i++) {
        const complement = target-nums[i]
        if(map.has(complement) && map.get(complement) !== i) {
            return [map.get(complement), i]
        }
    }
};

중첩 for문으로 처음 풀었던 것을 맵과 for문 두 개를 이용하여 시간복잡도를 낮추었다.

profile
You only have to right once

0개의 댓글