๐Ÿงฎ

Two Sum

Two Sum
๋ณดํ†ต ์•Œ๊ณ ๋ฆฌ์ฆ˜ +20pts

Problem

Given an array of numbers and a target, return the indices of two numbers that add up to the target.

Examples

Input: twoSum([2, 7, 11, 15], 9)
Output: [0, 1]
๐Ÿ’ก nums[0] + nums[1] = 2 + 7 = 9

Explanation

์ด ๋ฌธ์ œ๋Š” **ํ•ด์‹œ๋งต(Map)**์„ ํ™œ์šฉํ•œ ์ตœ์ ํ™” ๊ธฐ๋ฒ•์„ ํ•™์Šตํ•ฉ๋‹ˆ๋‹ค. LeetCode์˜ ๋Œ€ํ‘œ์ ์ธ ๋ฌธ์ œ๋กœ ์ฝ”๋”ฉ ์ธํ„ฐ๋ทฐ์— ์ž์ฃผ ๋“ฑ์žฅํ•ฉ๋‹ˆ๋‹ค. **๋ธŒ๋ฃจํŠธ ํฌ์Šค ์ ‘๊ทผ (O(nยฒ))** ์ด์ค‘ for๋ฌธ์œผ๋กœ ๋ชจ๋“  ์Œ์„ ํ™•์ธํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ๊ฐ„๋‹จํ•˜์ง€๋งŒ ๋น„ํšจ์œจ์ ์ž…๋‹ˆ๋‹ค. **ํ•ด์‹œ๋งต ์ตœ์ ํ™” (O(n))** ํ•ต์‹ฌ ์•„์ด๋””์–ด: "target - ํ˜„์žฌ๊ฐ’ = ๋ณด์ˆ˜(complement)" ๊ฐ ์ˆซ์ž๋ฅผ ๋ณผ ๋•Œ, ๊ทธ ์ˆซ์ž์˜ ๋ณด์ˆ˜๊ฐ€ ์ด๋ฏธ Map์— ์žˆ๋Š”์ง€ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค. **[2, 7, 11, 15], target=9 ์ฒ˜๋ฆฌ ๊ณผ์ •** - i=0, nums[0]=2: ๋ณด์ˆ˜=7, ...

View detailed explanation โ†’

Key Concepts

ํ•ด์‹œ๋งต(Map) ๋ณด์ˆ˜(complement) ๊ฐœ๋… ์‹œ๊ฐ„๋ณต์žก๋„ ์ตœ์ ํ™” ํ•œ ๋ฒˆ์˜ ์ˆœํšŒ
Time: O(n) Space: O(n)
solution.js
Ctrl + Enter
Run tests to see results here.