๐์ฃผ์๊ฐ๊ฒฉ - ํ๋ก๊ทธ๋๋จธ์ค Level2
- ์ฒซ ๋ฒ์งธ ํ์ด
def solution(prices): result = [0] * len(prices) temp = list(zip(prices, range(1, len(prices) + 1))) for te, nu in temp: for te2, nu2 in temp[nu:]: if te <= te2: result[nu - 1] += 1 else: result[nu - 1] += 1 break return result
- ๋ ๋ฒ์งธ ํ์ด
def solution(prices): result = [0] * len(prices) for i in range(len(prices)): for j in range(i + 1, len(prices)): if prices[i] <= prices[j]: result[i] += 1 else: result[i] += 1 break return result
- ์ธ ๋ฒ์งธ ํ์ด
def solution(prices): length = len(prices) result = [x for x in range(length - 1, -1, -1)] stack = [] for i in range(length): while stack and prices[i] < prices[stack[-1]]: temp = stack.pop() result[temp] = i - temp stack.append(i) return result
๋๋ฌด์ง stack์ ํ์ฉํ์ฌ ํ ๋ฐฉ๋ฒ์ด ๋ ์ค๋ฅด์ง ์์ ๋ค๋ฅธ ์ฌ๋์ ํ์ด๋ฅผ ์ฐธ๊ณ ํ์๋ค.
result ๋ฅผ ์ญ์์ผ๋ก ์ด๊ธฐํ ํ ์ด์ ๋ for ๋ฌธ์์์ ์์์ index 0 ์๋ฆฌ์ ์๋ 1 ๊ฐ์ ๊ฒฝ์ฐ๋ ๋ฆฌ์คํธ ์์์ 1๋ณด๋ค ์์์ง๋ ๊ฒฝ์ฐ๊ฐ ์์ด ์ซ์ ๊ฐฑ์ ์ด ๋์ง ๋ชปํ๋คresult = [0] * len(prices) #์๋ต while stack: temp = stack.pop() result[temp] = len(prices) - 1 - temp
์์ ๊ฐ์ ์์ผ๋ก ๋ง์ง๋ง์ stack์ ๋จ์์๋ ๋ถ๋ถ๋ค์ ์ฒ๋ฆฌํด์ค๋ ๋์ง๋ง ์ฒ์๋ถํฐ ์ญ์์ผ๋ก ์ด๊ธฐํ๋ฅผ ์ํจ๋ค๋ฉด ์์ ๊ฐ์ ์ ์ฒ๋ฆฌ ๋ถ๋ถ์ ์ํํ ํ์ ์์ผ๋ฏ๋ก ์ข์ ๊ฒ ๊ฐ๋ค.
ํ์คํ stack์ ์ฌ์ฉํ์ฌ ์คํ์ ํ๋ ํจ์จ์ฑ ํ ์คํธ์์ ์๊ฐ์ด ๋ง์ด ๋จ์ถ๋์๋ค.
๐ ํ๋ฆฐํฐ - ํ๋ก๊ทธ๋๋จธ์ค Level2
- ๋ด ํ์ด stack, queue ํ์ฉ (์ ๋ต)
from collections import deque def solution(priorities, location): stack = [[-1, -1]] temp = zip(priorities, range(len(priorities))) queue = deque(temp) while stack[-1][1] != location: value = queue.popleft() for pr, num in queue: if value[0] < pr: queue.append(value) break else: stack.append(value) return len(stack) - 1
- temp list์ ์ฃผ์ด์ง priorities ๊ฐ๊ณผ ํด๋น ๊ฐ์ location์ธ ์ธ๋ฑ์ค๋ฅผ zip์ ํ์ฉํ์ฌ ๊ฐ์ด ๋ฌถ์ด ์ฃผ์ด
- while ๋ฌธ์ ์ํํ ๋ stack ์ ๋ค์ด๊ฐ์๋ location ๊ฐ์ด ๋ฌธ์ ์์ ์ฃผ์ด์ง location๊ณผ ๊ฐ์ผ๋ฉด while ๋ฌธ์ ์ข ๋ฃํ๋ค.
- queue ์ผ์ชฝ(์๋ถ๋ถ) ์์ ํ๋ฆฐํธ ํด๋ ๋๋์ง value์ ์ ์ฅ์ ํ ํ
queue ์ ๋จ์์๋ ๊ฐ๋ค๊ณผ ๋น๊ต๋ฅผ ํ์ฌ ๋ ํฐ ๊ฐ์ด ์๋ค๋ฉด queue์ ๋งจ ๋ค๋ก ๋ณด๋ธ ํ for ๋ฌธ์ ์ข ๋ฃํ๋ค.- for๋ฌธ์์ ์ํ๋ ๊ฒ์ด ์๋ค๋ฉด else ๋ฌธ์ ํ stack์ ์ถ๊ฐํด์ค๋ค (ํ๋ฆฐํธ ๋๋ค)
- ํ์ด๋ฅผ ์ ์ผ๋ฉฐ ์๊ฐํด๋ดค๋๋ฐ stack์ ํ์ฉ์ ์ํ๋ค...ใ ใ
์ฒ์์ ๋ฌด์์ stack์ ํ์ฉํ์ฌ ํ์ด๋ณด์๋ ๋ชฉ์ ์ผ๋ก list ๋ณ์ ๋ช ์ stack์ผ๋ก ์ฌ์ฉํ์์ง๋ง ํ๊ณ ๋ณด๋ stack์ ์๋๊ฑธ๋ก...ใ
deque๋ฅผ ํ์ฉํ ํ์ด์ด๋ค.- ๋ ๋ฒ์งธ ํ์ด
from collections import deque def solution(priorities, location): stack = [] queue = deque([(x, y) for x, y in enumerate(priorities)]) cnt = 0 while 1: temp_num, temp_pr = queue.popleft() if any(temp_pr < x[1] for x in queue): queue.append((temp_num, temp_pr)) else: cnt += 1 if temp_num == location: return cnt
๋ค๋ฅธ ์ฌ๋์ ํ์ด๋ฅผ ํ์ฉํ ๊ฒ์ธ๋ฐ ๊ทธ ๋ถ์ deque๋ฅผ ์ฌ์ฉํ์ง ์๊ณ ์ผ๋ฐ ๋ฆฌ์คํธ์์ pop[0]์ ํ์ฌ ํ์ด๋ฅผ ํ์๋ค.
๋ pop[0] ์ ํ๊ฒ๋๋ฉด ์๊ฐ ๋ณต์ก๋๊ฐ N์ด ๋๊ธฐ๋๋ฌธ์ deque๋ฅผ ์ฌ์ฉํ์ฌ ๋ค์ ์๋ฃํ์ ๋ง๋ค์ด ์ฃผ์๊ณ
cnt ๊ฐ์ ์ค ๊ฒ๊ณผ any() ๋ฅผ ์ฌ์ฉํ๊ฒ์ด ๋์ ๋ค๋ฅธ ์ ์ด์๋ค.
ํ์คํ cnt๋ฅผ ์ฃผ๊ณ return์ ๋ฐ๋ก ํด์ฃผ๋ ๊น๋ํ๊ธฐ๋ ํ๋ค.
๋ช ๊ฐ ๋ ํ์ด๋ด์ผ๊ฒ ๋ค
์ค๋ ๋!