Two Sum

LeetCode ๋ฐ”๋กœ๊ฐ€๊ธฐ

๋ฌธ์ œ

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

๋ฌธ์ œ ์ดํ•ด

  • ์ฒซ๋ฒˆ์งธ ์ธ์ž๋กœ ์ˆซ์ž๋“ค๋กœ ์ด๋ฃจ์–ด์ง„ ๋ฐฐ์—ด์ด ๋“ค์–ด์˜ด

  • ๋‘๋ฒˆ์งธ ์ธ์ž๋Š” ์ฒซ๋ฒˆ์งธ ์š”์†Œ๋กœ ๋“ค์–ด์˜จ ๋ฐฐ์—ด์š”์†Œ์—์„œ 2๊ฐœ๋ฅผ ์ด์šฉํ•˜์—ฌ ๋”ํ•œ๊ฐ’์ด ๋‘๋ฒˆ์งธ ์ธ์ž ๊ฐ’์ด ๋˜์–ด์•ผ ํ•œ๋‹ค.

  • ๋ฆฌํ„ด๊ฐ’์€ [์ธ๋ฑ์Šค, ์ธ๋ฑ์Šค]

ํ•ด๊ฒฐ ๋ฐฉ๋ฒ•

  • for๋ฌธ์„ ๋Œ๋ ค ๋ฐฐ์—ด์„ ์ˆœํšŒํ•œ๋‹ค.

  • slice๋ฅผ ํ†ตํ•ด index + 1 ํ•œ ์š”์†Œ์—์„œ target์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ์š”์†Œ๋ฅผ ์ฐพ๋Š”๋‹ค.

์ฝ”๋“œ ๊ตฌํ˜„

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    for(let i = 0; i < nums.length; i++) {
        const number = target - nums[i];
        const index = nums.slice(i + 1).indexOf(number);
        if(index >= 0) return [i, index + i + 1];
    }
};

๊ฒฐ๊ณผ ๋ถ„์„

Runtime: 176 ms

Memory Usage: 41.1 MB

Last updated

Was this helpful?