[Programmers] ์ฒด์œก๋ณต

Updated:

์ฒด์œก๋ณต

์ฒด์œก๋ณต ์„ ํด๋ฆญํ•˜๋ฉด ๋ฐ”๋กœ ์ด๋™ํ•œ๋‹ค.

์ž‘๋…„ 7์›”์— ํ’€์—ˆ๋˜ ๋ฌธ์ œ์ด๋‹ค.

๊ทธ๋ฆฌ๋””๋ฅผ ๋‹ค์‹œ ํ’€์–ด๋ณด๊ณ  ์‹ถ์–ด ํ’€์—ˆ๋Š”๋ฐ..

์ž‘๋…„์— ๋‚˜๋Š” ์™œ ์ €๋ ‡๊ฒŒ ํ’€์—ˆ์„๊นŒ ์˜๋ฌธ์ด ๋“ ๋‹ค..

์šฐ์„  ๋ฌธ์ œ ์กฐ๊ฑด์„ ๋ณด๋ฉด ์—ฌ๋ถ„์˜ ์ฒด์œก๋ณต์„ ๊ฐ€์ ธ์™”์ง€๋งŒ ์žƒ์–ด๋ฒ„๋ฆฐ ์นœ๊ตฌ๋„ ์žˆ์„ ์ˆ˜ ์žˆ๋‹ค.

๊ทธ ์นœ๊ตฌ๋“ค์„ ์ œ์™ธ ํ•ด์ฃผ๊ณ  ์ฒด์œก๋ณต์„ ์žƒ์–ด๋ฒ„๋ฆฐ ์นœ๊ตฌ์— ๋Œ€ํ•ด ๋นŒ๋ ค ์ค„ ์ˆ˜ ์žˆ๋Š” ์นœ๊ตฌ๊ฐ€ ์žˆ์œผ๋ฉด ๋‘˜ ๋‹ค ์ง€์›Œ๊ฐ€๋ฉฐ ๊ณ„์‚ฐํ•œ๋‹ค.

def solution(n, lost, reserve):

	# ์—ฌ๋ถ„์„ ๊ฐ€์ ธ ์™”์ง€๋งŒ ์žƒ์–ด๋ฒ„๋ฆฐ ์‚ฌ๋žŒ ์ œ์™ธ
	intersection = set(lost).intersection(set(reserve))
	lost = list(set(lost) - intersection)
	reserve = list(set(reserve) - intersection)

	lost_person = len(lost)
	for per in lost:
		if per - 1 in reserve:
			lost_person -= 1
			reserve.remove(per - 1)
			continue

		if per + 1 in reserve:
			lost_person -= 1
			reserve.remove(per + 1)
			continue

	return n - lost_person

์•„์ง ์ฝ”๋“œ์˜ ๋ฐ˜ ์ •๋„๋งŒ ํŒŒ์ด์ฌ ๋‹ค์šด ๋Š๋‚Œ์ด ๋“ ๋‹ค !!

comprehension ๊ธฐ๋Šฅ์ด ์•„์ฃผ ๊ฐ•๋ ฅํ•˜๊ณ  ํŽธํ•œ ๊ฑธ ์•Œ๊ฒŒ ๋˜์—ˆ๋‹ค.

์›๋ž˜ ๋‚ด๊ฐ€ ์›ํ•˜๋Š” ๋ฐฉ์‹๋Œ€๋กœ dict ๋ฅผ ๋งŒ๋“ค๋ ค๋ฉด for ๋ฌธ ์•ˆ์— ์กฐ๊ฑด๋ฌธ์„ ์จ์„œ dict ๋ฅผ ๋งŒ๋“ค์–ด์•ผ ํ–ˆ์„ ๊ฒƒ ์ด๋‹ค.

def giveAndTakeCloth(perDict, key, n):
	if key == 1:
		if perDict[key+1] == 2:
			perDict[key+1] -= 1
			perDict[key] += 1

	elif key == n:
		if perDict[key-1] == 2:
			perDict[key-1] -= 1
			perDict[key] += 1

	else:
		if perDict[key-1] == 2:
			perDict[key-1] -= 1
			perDict[key] += 1

		if perDict[key+1] == 2:
			perDict[key+1] -= 1
			perDict[key] += 1

def solution (n, lost, reserve):
	answer = 0
	perDict = {i+1:(1 if i+1 in reserve and i+1 in lost else 2 if i+1 in reserve else 0 if i+1 in lost else 1) for i in range(n)}

	for key, val in zip(perDict.keys(), perDict.values()):
		if val == 0:
			giveAndTakeCloth(perDict, key, n)

	for val in perDict.values():
		if val >= 1:
			answer += 1

	return answer

reserve, lost ๋ฅผ ๊ฐ€์ง€๊ณ  ๋งจ ์ฒ˜์Œ ์˜ท์„ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ์ƒํƒœ์ธ dict ๋ฅผ ๋งŒ๋“ค๊ณ  ๊ณ„์‚ฐ์„ ํ–ˆ๋‹ค.

๋ฌด์กฐ๊ฑด ์™ผ์ชฝ๋จผ์ € ์ฃผ๋Š” ๋ฐฉํ–ฅ์œผ๋กœ ์ฝ”๋”ฉ์„ ํ–ˆ๋‹ค.

๊ทธ๋Ÿฐ๋ฐ ๊ทธ๋ ‡๊ฒŒ ํ•˜๋ฉด ๋งจ ์™ผ์ชฝ ์‚ฌ๋žŒ, ๋งจ ์˜ค๋ฅธ์ชฝ ์‚ฌ๋žŒ์˜ ๊ฒฝ์šฐ key ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒ ํ•ด ๋”ฐ๋กœ ๊ฒฝ์šฐ๋ฅผ ๋‚˜๋ˆ„์–ด ์คฌ๋‹ค.

๋ถ„๋ช…~ํžˆ ๋” ์ข‹์€ ๋ฐฉ๋ฒ•์œผ๋กœ ์ค„์ผ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์€๋ฐ ์•„์ง ์ƒ๊ฐ์ด ์•ˆ๋‚œ๋‹ค..

๊ทธ๋ฆฌ๊ณ  ๋‹ค๋ฅธ ์‚ฌ๋žŒ๋“ค์˜ ์ฝ”๋“œ๋ฅผ ๋ณด๋‹ˆ๊นŒ ์‚ฌ๋žŒ ๋ฒˆํ˜ธ ์ž์ฒด๋ฅผ ํ†ตํ•ด ์˜ท์„ ์ฃผ๊ณ , ๋ฐ›์•„์„œ lost, reverse ์—์„œ remove ํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ๊ตฌํ–ˆ๋‹ค.

์ง„์งœ ๋ฉ‹์žˆ๋Š” ์‚ฌ๋žŒ๋“ค..


Categories:

Updated:

Leave a comment