๐งฎ
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.