๐ŸŒฑ → ๐ŸŒณ

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์™„์ฃผํ•˜์ง€ ๋ชปํ•œ ์„ ์ˆ˜ - python ๋ณธ๋ฌธ

Algorithms

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์™„์ฃผํ•˜์ง€ ๋ชปํ•œ ์„ ์ˆ˜ - python

BAY 2023. 8. 2. 13:07
728x90

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

 

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

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

programmers.co.kr

์„ค๊ณ„ ๋ฐฉ๋ฒ•

completion ๋Œ๋ฉด์„œ participant์— i๊ฐ€ ์žˆ์œผ๋ฉด completion ๋ฐฐ์—ด์—์„œ i ์ง€์›Œ์ฃผ๊ณ , ๋งˆ์ง€๋ง‰ ๋‚จ์€ participant๋ฅผ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋ฉด ๋œ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ์Œ

๊ทผ๋ฐ ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ์‹œ๊ฐ„๋ณต์žก๋„๊ฐ€ O(n^2) ์ด๊ธฐ ๋•Œ๋ฌธ์— ์‹œ๊ฐ„์ดˆ๊ณผ๋ฐœ์ƒ

 

๋ฌธ๋“ python ๋‚ด์žฅ sort() ํ•จ์ˆ˜๊ฐ€ O(nlogN)์ธ ๊ฒŒ ๊ธฐ์–ต๋‚ฌ์Œ

๋‚ด์žฅํ•จ์ˆ˜ ์‚ฌ์šฉํ•ด์„œ ์ •๋ ฌํ•œ ๋’ค, ์ˆœ์„œ๋Œ€๋กœ ๋นผ๋ฉด ๋˜๊ฒ ๊ตฌ๋‚˜ ์ƒ๊ฐํ•จ

์ฝ”๋“œ

์‹œ๊ฐ„์ดˆ๊ณผ

def solution(participant, completion):
    for i in completion:
        if i in participant:
            participant.remove(i)
    return participant[0]

๋‚˜์˜ ํ’€์ด์ฝ”๋“œ

from collections import deque
def solution(participant, completion):
    participant.sort()
    completion.sort()
    completion.append('0')
    for i in range(len(participant)):
        if participant[i] != completion[i]:
            return participant[i]
def solution(participant, completion):
    participant.sort()
    completion.sort()
    for i in range(len(completion)):
        if participant[i] != completion[i]:
            return participant[i]
    return participant[len(participant)-1]

ํ•ด์‹ฑ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์‚ฌ์šฉ ์ฝ”๋“œ

def solution(participant, completion):
    answer = ''
    temp = 0
    dic = {}
    for part in participant:
        dic[hash(part)] = part
        temp += int(hash(part))
    for com in completion:
        temp -= hash(com)
    answer = dic[temp]

    return answer

 

์ฐธ๊ณ 

Python์˜ sort() ๋‚ด์žฅ ํ•จ์ˆ˜์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” ๋ณดํ†ต O(n log n)์ž„

Python์˜ sort() ํ•จ์ˆ˜๋Š” Timsort๋ผ๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ๊ธฐ๋ฐ˜์œผ๋กœ ๋™์ž‘ํ•จ

Timsort๋Š” ๋ณ‘ํ•ฉ ์ •๋ ฌ(Merge Sort)๊ณผ ์‚ฝ์ž… ์ •๋ ฌ(Insertion Sort)์˜ ์กฐํ•ฉ์œผ๋กœ ๊ตฌ์„ฑ๋˜์–ด ์žˆ์œผ๋ฉฐ, ์ตœ์„ ์˜ ๊ฒฝ์šฐ์—๋Š” O(n)์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ๊ฐ€์ง€์ง€๋งŒ, ์ผ๋ฐ˜์ ์œผ๋กœ ํ‰๊ท ์ ์ธ ๊ฒฝ์šฐ์—๋Š” O(n log n)์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ๊ฐ€์ง

Timsort๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ์—ฌ๋Ÿฌ ๋ถ€๋ถ„์œผ๋กœ ๋‚˜๋ˆ„๊ณ , ๊ฐ ๋ถ€๋ถ„์— ๋Œ€ํ•ด ์ •๋ ฌ ํ›„ ๋ณ‘ํ•ฉํ•˜๋Š” ๊ณผ์ •์„ ๋ฐ˜๋ณตํ•˜์—ฌ ์ „์ฒด ๋ฆฌ์ŠคํŠธ๋ฅผ ์ •๋ ฌํ•จ. ์ •๋ ฌ๋œ ์ž‘์€ ๋ถ€๋ถ„ ๋ฆฌ์ŠคํŠธ๋“ค์„ ๋ณ‘ํ•ฉํ•˜๋Š”๋ฐ ํ•„์š”ํ•œ ์‹œ๊ฐ„์ด O(n)์ด๊ณ , ๋ถ„ํ• ํ•˜๋Š” ๊ณผ์ •์ด O(log n)๋ฒˆ ๋ฐœ์ƒํ•˜๋ฏ€๋กœ, ์ตœ์ข…์ ์œผ๋กœ ํ‰๊ท ์ ์ธ ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” O(n log n)์ด ๋˜๋Š” ๊ฒƒ 

ํ•˜์ง€๋งŒ, ๋ฆฌ์ŠคํŠธ์˜ ํฌ๊ธฐ๊ฐ€ ์ž‘์€ ๊ฒฝ์šฐ์—๋Š” ์‚ฝ์ž… ์ •๋ ฌ๊ณผ ์œ ์‚ฌํ•œ ์ž‘์€ ํฌ๊ธฐ์˜ ๋ถ€๋ถ„ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ •๋ ฌํ•˜๋Š” ๊ณผ์ •์ด ๋” ๋น ๋ฅด๊ธฐ ๋•Œ๋ฌธ์—, ์ตœ์„ ์˜ ๊ฒฝ์šฐ์—๋Š” O(n)์˜ ์„ฑ๋Šฅ์„ ๋ณด์—ฌ์ค„ ์ˆ˜ ์žˆ์Œ

728x90