
์๊ฐ ๋ฐฉ์
Brute Force๋ก ํ์๋ฉด for loop์ ๋ ๋ฒ ์จ์ ํ๋ฉด ๋๋ค.
๊ทผ๋ฐ ๋ Time complexity๊ฐ ์ข์ ์ฝ๋๋ฅผ ์ด๋ป๊ฒ ์ง๋ฉด ์ข์๊น?
๐ป ์ผ๋จ Brute Force๋ก ์์ฑํ ์ฝ๋
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
sums = []
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target:
sums.append(i)
sums.append(j)
return sums
์ ์ ํ์๋ ๋ฌธ์ ๋ฅผ ํ ๋๋ก HashMap์ ์ฌ์ฉํ๋ค๋ฉด ์ข ๋ ์ข๋ค๋ ๊ฒ์ ์๊ณ ์์ง๋ง ์ด๋ป๊ฒ ์ง์ผ ํ ์ง ๊ณ ๋ฏผ์ด ๋ง์๋ค
ํํธ๋ฅผ ๋ณด๊ณ ์กฐ๊ธ ์๊ฐ์ ํ๋ ๋๊ฒ ๊ฐ๋จํ๋ค [์ข ๋ ๋ค์ํ ์๊ฐ์ผ๋ก ๋ณด๋ฉด ๋๋ค...]
*๐กHint: diff = target - num
์ฌ๊ธฐ์ enumerate()๋ฅผ ์ฌ์ฉํ๋๋ฐ,
enumerate()๋ iterator์ด์ง๋ง index์ element๋ฅผ ๊ฐ์ด ๋ฆฌํดํด์ค๋ค๊ณ ํ๊ต์์ ๋ฐฐ์ด ๊ธฐ์ต์ด ๋ฌ๋ค.
๐ป ๋ค์ ์์ฑํ ์ฝ๋
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashMap = {}
for idx, num in enumerate(nums):
diff = target - num
if diff in hashMap:
return [hashMap[diff], idx]
hashMap[num] = idx
return
ํด์ค
hashMap์๋ value ๊ทธ๋ฆฌ๊ณ index๊ฐ ์์ ์์
์ฒซ ๋ฒ์งธ test case๋ฅผ ์๋ฅผ ๋ค์ด์ ๋ฃจํ๋ฅผ ๋ฏ์ด๋ณด๋ฉด
1st loop (idx = 0, num = 2):
* diff = target - num = 7, ์ฐ๋ฆฌ๊ฐ ์ฐพ์์ผ ํ๋ ์ซ์๋ 7์ด๋ค
* 7์ ์ฐ๋ฆฌ hashMap์ ์์ง ์๋ค
* ๊ทธ๋ฌ๋ฏ๋ก ์ฐ๋ฆฌ๋ hashMap[num] = idx๋ฅผ ํตํด value์ธ 2๋ฅผ ์ถ๊ฐํด์ฃผ๊ณ index๋ 0์ด๋ผ๋ ๊ฒ์ ์ถ๊ฐํด์ค๋ค
2nd loop (idx = 1, num = 7):
* diff = target - num = 2
* 2๋ ์ฐ๋ฆฌ hashMap์ ์๋ค
* ๊ทธ๋ฌ๋ฏ๋ก return์ ํด์ฃผ๋ฉด ๊น๋ํ๊ฒ ํด๊ฒฐ๋๋ค
hashMap[diff] ๋ ์๊น ์ ์ฅํ index 0์ด ๋๋ค, ๊ทธ๋ฆฌ๊ณ ์ง๊ธ idx๋ 1 ๊ทธ๋์ return ๊ฐ์ [0,1]์ด ๋๋ค

'์ฝ๋ฉ ํ ์คํธ > leetcode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| 746. Min Cost Climbing Stairs (Easy) [Python] (0) | 2024.02.04 |
|---|---|
| 70. Climbing Stairs (Easy) [Python] (2) | 2024.02.03 |
| 49. Group Anagrams (Medium) [Python] (0) | 2024.02.03 |
| 242. Valid Anagram (Easy) [Python] (0) | 2024.02.03 |
| 217. Contains Duplicate (Easy) [Python] (0) | 2024.02.03 |