๐Ÿ’ป Coding/[Algorithm]Python

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค | ๋‹ฌ๋ฆฌ๊ธฐ ๊ฒฝ์ฃผ โญ - Python

๐Ÿฉท ๋ฏผ์˜ 2024. 4. 4. 23:32

๐Ÿ—’๏ธ ๋ฌธ์ œ

https://school.programmers.co.kr/learn/courses/30/lessons/178871

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

๐Ÿ’ก์•„์ด๋””์–ด

1๏ธโƒฃ ์ฒซ ๋ฒˆ์งธ ํ’€์ด

callings๋ฅผ ๋ฐ˜๋ณตํ•ด์„œ players์™€ ๊ฐ’์ด ๊ฐ™์œผ๋ฉด ๊ทธ์ „ ๊ฐ’๊ณผ ์ž๋ฆฌ๋ฅผ ๋ฐ”๊ฟ”์ค€๋‹ค
=> ์‹œ๊ฐ„ ์ดˆ๊ณผ
 

2๏ธโƒฃ ๋‘ ๋ฒˆ์งธ ํ’€์ด

๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ๋งŒ๋“ค์–ด์„œ callings ๊ฐ’์ด ๋‚˜์˜ฌ ๋•Œ๋งˆ๋‹ค values ๊ฐ’์„ -1 ํ•ด์ค€๋‹ค
์ด๋•Œ, ๋”•์…”๋„ˆ๋ฆฌ๋Š” ์ธ๋ฐ์Šค๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š”๋‹ค๋Š” ์‚ฌ์‹ค์„ ์žŠ์ง€ ๋ง์ž!
 

โœ๏ธ ๋‚ด ํ’€์ด

์‹œ๊ฐ„ ์ดˆ๊ณผ ํ’€์ด

# ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ํ’€๊ธฐ 1์ฐจ์‹œ๋„
def solution(players, callings):
    for i in range(len(callings)):
        for j in range(1, len(players)):
            if players[j] == callings[i]:
                players[idx], players[idx-1] = players[idx-1], players[idx]
    # print(players)
    answer = players
    return answer
# ๋ฐ˜๋ณต๋ฌธ 2์ฐจ์‹œ๋„
def solution(players, callings):
    for i in callings:
        idx = players.index(i)
        players[idx], players[idx-1] = players[idx-1], players[idx]
    answer = players
    return answer

 
์„ฑ๊ณตํ•œ ํ’€์ด

def solution(players, callings):
	# ํ”Œ๋ ˆ์ด์–ด๋“ค์˜ ์ธ๋ฑ์Šค์— ๋”ฐ๋ผ ๋”•์…”๋„ˆ๋ฆฌ ์ƒ์„ฑ
    players_dic = {player : index for index, player in enumerate(players)}
    
    # callings๋ฅผ ๋ฐ˜๋ณตํ•ด์„œ calling์— ๋งž์ถ”์–ด values ๊ฐ’ -1
  	## players๋ฅผ key๊ฐ’์œผ๋กœ ์ด์šฉํ•ด์•ผํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๊ผญ players ๋ฆฌ์ŠคํŠธ ์ˆœ์„œ ๋ณ€๊ฒฝํ•ด์ฃผ๊ธฐ
    for calling in callings:
        index = players_dic[calling]
        players_dic[calling] -= 1
        players_dic[players[index - 1]] += 1
        players[index-1], players[index] = players[index], players[index-1]
    
    return players

 

๐Ÿ˜Š ํ›„๊ธฐ

์„ธ ํ’€์ด๋กœ ์‹œ๊ฐ„๋ณต์žก๋„์— ๋Œ€ํ•ด ์ƒ๊ฐํ•ด ๋ณผ ์ˆ˜ ์žˆ์—ˆ๋‹ค.
ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ํ…Œ์ŠคํŠธ์ผ€์ด์Šค์—์„œ๋Š” 1-2 ํ’€์ด๊ฐ€ ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋œ ์ง„ํ–‰๋๋‹ค ๊ทธ๋Ÿฌ๋‚˜, players.index(i)์˜ ๊ฒฝ์šฐ ํ˜ธ์ถœํ•  ๋•Œ๋งˆ๋‹ค ์ˆœ์ฐจ๊ฒ€์ƒ‰* ์ˆœ์ฐจ ๊ฒ€์ƒ‰ : ์ฒ˜์Œ๋ถ€ํ„ฐ ํ•˜๋‚˜์”ฉ ์ฐจ๋ก€๋Œ€๋กœ ๊ฒ€์ƒ‰ํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ˆ˜ํ–‰ํ•˜๋ฏ€๋กœ players์˜ ํฌ๊ธฐ๊ฐ€ ๋งค์šฐ ์ปค์ง€๊ฒŒ ๋˜๋ฉด ์˜คํžˆ๋ ค ๋” ์„ฑ๋Šฅ์ด ์ €ํ•˜๋  ์ˆ˜๋„ ์žˆ๋‹ค.
์ฆ‰, ๋ฐ˜๋ณต๋ฌธ์„ ์ด์šฉํ•œ 1-1, 1-2 ํ’€์ด๋Š” ์•ฝ O(n*m)์˜ ์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ ๊ฐ€์ง€๊ฒŒ ๋˜๋ฉฐ, ๋งˆ์ง€๋ง‰ ํ’€์ด์˜ ๊ฒฝ์šฐ O(n)์˜ ์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ ๊ฐ€์ง€๊ฒŒ ๋œ๋‹ค.