[CodeKata] Week1 - Day1

ใ…Žใ…Žยท2021๋…„ 6์›” 21์ผ
0

algorithm ํ’€์ด

๋ชฉ๋ก ๋ณด๊ธฐ
35/44
post-custom-banner

๐Ÿ“Œ CodeKata - Week1, Day1

๋ฌธ์ œ

two_sumํ•จ์ˆ˜์— ์ˆซ์ž ๋ฆฌ์ŠคํŠธ์™€ 'ํŠน์ • ์ˆ˜'๋ฅผ ์ธ์ž๋กœ ๋„˜๊ธฐ๋ฉด, ๋”ํ•ด์„œ 'ํŠน์ • ์ˆ˜'๊ฐ€ ๋‚˜์˜ค๋Š” index๋ฅผ ๋ฐฐ์—ด์— ๋‹ด์•„ returnํ•ด ์ฃผ์„ธ์š”.

nums: ์ˆซ์ž ๋ฐฐ์—ด
target: ๋‘ ์ˆ˜๋ฅผ ๋”ํ•ด์„œ ๋‚˜์˜ฌ ์ˆ˜ ์žˆ๋Š” ํ•ฉ๊ณ„
return: ๋‘ ์ˆ˜์˜ index๋ฅผ ๊ฐ€์ง„ ์ˆซ์ž ๋ฐฐ์—ด

์˜ˆ๋ฅผ ๋“ค์–ด,

nums์€ [4, 9, 11, 14]
target์€ 13 

nums[0] + nums[1] = 4 + 9 = 13 ์ด์ฃ ?

๊ทธ๋Ÿฌ๋ฉด [0, 1]์ด return ๋˜์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

๊ฐ€์ • : target์œผ๋กœ ๋ณด๋‚ด๋Š” ํ•ฉ๊ณ„์˜ ์กฐํ•ฉ์€ ๋ฐฐ์—ด ์ „์ฒด ์ค‘์— 2๊ฐœ ๋ฐ–์— ์—†๋‹ค๊ณ  ๊ฐ€์ •ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.

ํ’€์ด1

def two_sum(nums, target): # ๋ฆฌ์ŠคํŠธ, ๋ฆฌ์ŠคํŠธ์ด ๋‘์ˆ˜๋ฅผ ๋”ํ–ˆ์„ ๋•Œ ๋‚˜์˜ค๋Š” ํ•ฉ๊ณ„
    arr = [] # ๋‹ต์„ ๋„ฃ๊ธฐ ์œ„ํ•ด 
    length = len(nums) 
    for i in range(length):
        for j in range(length):
            if  nums[i] + nums[j]  == target:
                arr.append(i)
                arr.append(j)
                return arr

โžก๏ธ ์ฒ˜์Œ์— ์žฌ๊ฒฝ๋‹˜์ด๋ž‘ ํ’€์—ˆ๋˜ ๋ฐฉ์‹. ๋นˆ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋งŒ๋“ค๊ณ  ์ •๋‹ต ํ•˜๋‚˜์”ฉ ์ถ”๊ฐ€ํ•˜๊ณ  nums์˜ ๊ธธ์ด๋„ ๋”ฐ๋กœ ๊ตฌํ•ด ๋ณ€์ˆ˜์— ๋„ฃ์–ด์คŒ.

ํ’€์ด2

def two_sum(nums, target): # ๋ฆฌ์ŠคํŠธ, ๋ฆฌ์ŠคํŠธ์ด ๋‘์ˆ˜๋ฅผ ๋”ํ–ˆ์„ ๋•Œ ๋‚˜์˜ค๋Š” ํ•ฉ๊ณ„
    for i in range(0, len(nums)):
        for j in range(i +1 , len(nums)): #์ค‘๋ณต์„ ๋ง‰๊ธฐ ์œ„ํ•ด i+1์„ ์‹œ์ž‘์ ์œผ๋กœ 
            if nums[i] + nums[j] == target:
                return [i,j] #๋ฆฌ์ŠคํŠธํ˜•์œผ๋กœ return

โžก๏ธ ์œ„์˜ ๋ฐฉ์‹์—์„œ ํ•„์š”์—†๋Š” ์ฝ”๋“œ๋Š” ๋นผ๊ณ  ๋‹ค์‹œ ํ‘ผ ๋ฐฉ๋ฒ•

post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€