https://leetcode.com/problems/two-sum/submissions/
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
๋ด๊ฐ ํผ๊ฑฐ:
class Solution(object):
def twoSum(self, nums, target):
result = [];
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i] + nums[j] == target :
return [i,j]
return []
range ์ enumerate ์ฐจ์ด์
- range(start, stop, step) ๋ฆฌ์คํธ์ index ์์, ๋, ๊ฐ๊ฒฉ ์ค์
- enumerate() - for๋ฌธ์์ index,value ๋ฅผ ๊ฐ์ด ์ ์ ์์ ํด๋น ์ธ๋ฑ์ค์ ์๋ ๋ฐ์ดํฐ๋ฅผ ์กฐ์ํ ๋ ์ ์ฉํ ๊ฒ ๊ฐ๋ค.
๊ด์ฐฎ๋ค๊ณ ์๊ฐํ ํ์ด ์ค ํ๊ฐ:
finder = defaultdict()
for i, num in enumerate(nums):
if target - num in finder:
return [finder[target - num],i ]
finder[num] = i
return [-1, -1]
์ด๊ฑฐ ์ดํดํ๊ธฐ๊ฐ ์ด๋ ค์ ๋ค.
๋ง์ฝ target ์ด 9 ์ด๊ณ 9๋ฅผ ๊ตฌ์ฑํ๋ ์ฌ๋ฌ๊ฐ ์ค 5,4๊ฐ ์๋ค๊ณ ํ๋ค๋ฉด
for ๋ฌธ์ ๋๋ฉด์
9-4 (key) = 5
9-5 (key) = 4
1. 4๋ฅผ key ๋ก ๊ฐ๊ณ ์๋ dict ๊ฐ ์๋ค.
2. if ๋ฌธ์์ ํ์ฌ๊ฐ 5 ๋ฅผ 9์์ ๋นผ๋ฉด 4๊ฐ ๋์ค๋ ์ด๋ฏธ 4๋ฅผ ๊ฐ๊ณ ์๋ Key ๊ฐ ์๋ค.
3. ์กฐํฉ ์ฑ๊ณตํ์ฌ ์ ์ฅ index ์ ํ์ฌ index ๋ฅผ ๋ฐํํ๋ค.
์ดํด๊ฐ ์ ๊ฐ๋ ๋ถ๋ถ์ finder[num] = i ์ด๋ ๊ฒ ํ๋ฉด ๋ฎ์ด์ง๋ ๊ฑด ์ค ์์๋๋ฐ ์ถ๊ฐ๋๋ ๊ฑฐ์๋ค...
defaultdict() ๊ฐ ๋ญ์ง?
๊ธฐ๋ณธ ๊ฐ์ ๊ฐ์ง ๋์ ๋๋ฆฌ ์์ฑํ๋ค.
ํ์ง๋ง ์ด๊ธฐ๊ฐ์ ์ค์ ํ์ง ์์๋ ๋๋ค. ์ฒจ๋ถํฐ ํค๋ฅผ ๊ฒ์ฌํ๊ฑฐ๋ ์ด๊ธฐ๊ฐ์ ํ ๋นํ ํ์ ์์. (์ฝ๋ ๊ฐ๊ฒฐ)
dict ์ list ์ ์ฐจ์ด์ ์ด ๋ญ์ง?
dict ๋ ํค-๊ฐ ๊ตฌ์กฐ์ด๋ฉฐ ํน์ ํค์ ๋ํ ๊ฐ์ ๋น ๋ฅด๊ฒ ๊ฒ์ํ๊ฑฐ๋ ์์ ํ๋ค. ex. {"name":"aejeong"}
list ๋ ํญ๋ชฉ ์ถ๊ฐ, ์์ , ์ญ์ , ์์ฐจ์ ์ธ ๋ฐ์ดํฐ ์ ์ฅ์ ์ฉ์ดํ๋ค. ex. ["aejeong"]
'์๊ณ ๋ฆฌ์ฆ > Python' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
347. Top K Frequent Elements (0) | 2023.08.20 |
---|---|
49. Group Anagrams (0) | 2023.08.18 |
242. Valid Anagram (0) | 2023.08.13 |
217. Contains Duplicate (0) | 2023.08.10 |