๐ programmers ์ฒด์ก๋ณต ๊ทธ๋ฆฌ๋ ๋ฌธ์ ์ด๋ค.
๋๋ ๋ฌธ์ ์ ํ์๋ฒํธ๋ฅผ ์ธ๋ฑ์ค๋ก, ๊ทธ ๊ฐ์ ์ฒด์ก๋ณต์ ์๋ก ํ์ฌ ๋ฆฌ์คํธ๋ก ํํํด ์ค ํ 0 ์ธ ์น๊ตฌ๋ค์ ์์์ด 2์ธ ์น๊ตฌ๋ค์ด ์์ผ๋ฉด ๋น๋ฆด ์ ์๊ฒ(์ผ์ชฝ๋ถํฐ) ์ง๋ดค๋ค.
- ํ์ด 1
def solution(n, lost, reserve): temp = [1 for _ in range(n + 2)] temp[0] = 0 temp[-1] = 0 for lo in lost: temp[lo] = 0 for re in reserve: if temp[re] == 0: temp[re] = 1 continue temp[re] = 2 for i in range(1, n + 1): if temp[i] == 0: if temp[i-1] == 2: temp[i-1] -= 1 temp[i] = 1 elif temp[i+1] == 2: temp[i+1] -= 1 temp[i] = 1 return sum([1 for x in temp if x != 0])
๋ฌธ์ ๋ฅผ ํธ๋ ๋์ค and or ๋ฌธ์ ์ฌ์ฉํ์ฌ ๋ฌธ์ ๋ฅผ ๋ณต์กํ๊ฒ ํ์์๋๋ฐ ๋ฌธ์ ๊ฐ ์ ํ๋ ค ๋ค๋ฅธ ์์ ํ์ด๋ก๋ ํ์๋ค.
temp list๋ฅผ ๋ง๋๋ ๊ณผ์ ๊น์ง๋ ๊ฐ์ง๋ง ๊ทธ ๋ค ๋น๋ฆฌ๋ ๊ณผ์ ์ ์กฐ๊ธ ๋ค๋ฅด๋ค
์์ ํ์ด๋ ๋ชจ๋ ํ์ list๋ฅผ ๋๋ ๊ฒ์ด์ง๋ง ๋ ๋ฒ์ฌ ํ์ด๋ ์์ด๋ฒ๋ฆฐ ํ์๋ค์ ๋ฆฌ์คํธ๋ฅผ ๋ง๋ค์ด ์ค ํ ํธ๋ ๊ฒ์ด๋ค.
- ํ์ด 2
def solution(n, lost, reserve): temp = [1 for _ in range(n + 2)] temp[0] = 0 temp[-1] = 0 for lo in lost: temp[lo] = 0 for re in reserve: if temp[re] == 0: temp[re] = 1 continue temp[re] = 2 n_lost = [x for x in range(1, n + 1) if temp[x] == 0] for lo in n_lost: if temp[lo-1] == 2: temp[lo-1] = 1 temp[lo] = 1 elif temp[lo+1] == 2: temp[lo+1] = 1 temp[lo] = 1 return sum([1 for x in temp if x != 0])
์ฃผ์ด์ง ํ์์ ์๊ฐ ์ต๋ 30๋ช ๊น์ง์ฌ์ ํ์ ๋ฆฌ์คํธ ์ ์ฒด๋ฅผ ๋ค ๋๋ค ํด๋ ์๊ฐ ๋ณต์ก๋๋ ๊ธธ์ง ์์ ๊ฒ์ด๋ฉฐ ๋ฌธ์ ์์ฒด๊ฐ ์๊ฐ๋ณต์ก๋ ์๊ตฌ ์กฐ๊ฑด์ด ๋น ๋ฏํ์ง ์์ 1๋ ๋ฒจ ๋ฌธ์ ๋ผ ์ด๋ค ๋ฐฉ์์ผ๋ก ํ์ด๋ ์๊ด์๋ค.
ํ
๋ฌธ์ ๋ฅผ ์ ์ฝ์ด์ผ ํ๋๋ฐ ์ฒด์ก๋ณต์ ์์ด๋ฒ๋ฆฐ ํ์๊ณผ ๋ ๊ฐ์ ธ์จ ํ์์ด ๊ฒน์น ์ ์์ด ๊ทธ ์ฒ๋ฆฌ๋ฅผ ํด์ฃผ์ด์ผ ํ๋ค.์ก๋ด
๊ฒ์์ ํด๋ณด๋ ๋ค๋ฅธ ์ฌ๋๋ค์ remove๋ฅผ ์ฌ์ฉํ์ฌ ๋ฌธ์ ๊ฒน์น๊ฑฐ๋ ๋น๋ ค์ค ํ์์ ๋นผ ์ฃผ์๋๋ฐ ์๊ณ ๋ฆฌ์ฆ ๋ฌธ์ ๋ฅผ ํ๋ค๋ณด๋ remove() ํจ์๋ ๋๋๋ก ์ฌ์ฉํ๊ณ ์ถ์ง ์์์ ์ ๊ฑฐ ํด์ผํ๋ ๋ฌธ์ ๊ฐ list, dict ๋ฅผ ๋ง๋ค์ด์ฃผ์ด ํํํ๋ ํธ์ด๋ค. ๊ทธ๊ฒ ์ข๋ค.
๐ programmers [1์ฐจ] ๋น๋ฐ์ง๋ ์นด์นด์ค 2018 ๋ ๋ ๋ฌธ์ ๋ผ์ ์ฌ์ด ๋ฌธ์ ์ด๋ค.
- ํ์ด
def solution(n, arr1, arr2): result = [] for ar1, ar2 in zip(arr1, arr2): line1 = format(ar1, 'b') line2 = format(ar2, 'b') temp = int(line1) + int(line2) temp = str(temp) while len(temp) != n: temp = '0' + temp temp = temp.replace('0', ' ') temp = temp.replace('1', '#') temp = temp.replace('2', '#') result.append(temp) return result
๐ ๋ด velog algorithm ๊ฐ์ฅ ํฐ ์ ์ ์๋์๋์ง ์์๋ค.
21 ๊ณผ 212 ๋ฅผ ๋น๊ตํ์์๋๋ 2122, 2122 ๋๊ฐ์ด ๋์ ๋๋คํ๊ฒ ๋ฐฐ์น๋๋ฏ๋ก ํ๋ฆฐ ๋ฐฉ๋ฒ์ด์๋ค. ๋ด ๋ฐฉ์๋๋ก ํ๋ ค๋ฉด 212๋ 212212 ๋ก 21์ 212121 ๋ก ๋ฐ๊พธ์ด ๊ณ์ฐ์ ํด์ฃผ์ด์ผ ํ๋๋ฐ ๊ทธ๋ผ 1 ~ 1000 ๊น์ง ์์๊ฐ ๋ค์ด์ค๋ฏ๋ก ์ต๋ 8์๋ฆฌ๊น์ง ๋ง๋ค๊ณ ๋ค์ด์จ ์ซ์์ ํฌ๊ธฐ๋งํผ ๋ฐ๋ณตํด์ฃผ์ด์ผ ํ๋ฏ๋ก ๋ฌด์...
์ซ์ ๋ฌธ์์ด์ ์๋ก ๋น๊ตํ ๋๋ ์์คํค ์ฝ๋๋ก ๋น๊ตํ๋ ๊ฒ์ ์์๊ฐ ๊ฒ๋ง ํด๋ ์ข์ ์ฑ๊ณผ๋ค.