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].
๋ฌธ์ ์ดํด
์ฒซ๋ฒ์งธ ์ธ์๋ก ์ซ์๋ค๋ก ์ด๋ฃจ์ด์ง ๋ฐฐ์ด์ด ๋ค์ด์ด
๋๋ฒ์งธ ์ธ์๋ ์ฒซ๋ฒ์งธ ์์๋ก ๋ค์ด์จ ๋ฐฐ์ด์์์์ 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?