๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
โญ Problem_Solving/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๊ณ ๋“์  kit - ํ•ด์‹œ

by ํฌ์ŠคํŠธ์‰์ดํฌ 2023. 1. 14.

<๋ฌธ์ œ๋งํฌ>

https://school.programmers.co.kr/learn/courses/30/parts/12077

 

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

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

programmers.co.kr

 

<ํ’€์ด ์ „๋žต>

1. ์™„์ฃผํ•˜์ง€ ๋ชปํ•œ ์„ ์ˆ˜: ๋™๋ช…์ด์ธ ๋•Œ๋ฌธ์— set์„ ์“ฐ๋ฉด ์•ˆ๋˜๊ณ  dict์ด๋‚˜ counter ์ž๋ฃŒํ˜•์„ ์จ์•ผํ•œ๋‹ค. hash ์ž๋ฃŒํ˜•์„ ์•ˆ ์“ฐ๊ณ  ๊ทธ๋ƒฅ list๋‚˜ zip๋“ฑ์„ ์จ๋„ ํ†ต๊ณผ๋œ๋‹ค.

2. ํฐ์ผ“๋ชฌ: set์„ ์“ฐ๋ฉด ์‰ฝ๋‹ค

3. ์ „ํ™”๋ฒˆํ˜ธ ๋ชฉ๋ก: ํ•ด์‰ฌ๋ฅผ ์•ˆ ์“ฐ๊ณ  list๋ฅผ ์จ์„œ O(N)์— ํ’€์ดํ–ˆ๋‹ค. ํ•ด์‰ฌ๋ฅผ ์“ด ํ’€์ด๋„ ๋ดค๋Š”๋ฐ ๊ทธ๋ƒฅ list๋ฅผ ์“ฐ๋Š” ๊ฒŒ ๋” ์‰ฌ์šธ ๊ฒƒ ๊ฐ™๋‹ค

4. ์œ„์žฅ: defaultdict์„ ํ™œ์šฉํ–ˆ๋‹ค. ์ „์ฒด ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ํŒŒ์•…ํ•˜๋Š” ๊ณผ์ •์ด ์žˆ์–ด์„œ ํ•ด์‰ฌ๋ณด๋‹ค ์ˆ˜ํ•™ ๋ฌธ์ œ์— ๋” ๊ฐ€๊นŒ์šด ๋ฌธ์ œ

5. ๋ฒ ์ŠคํŠธ์•จ๋ฒ”: sort์˜ key๊ฐ’์œผ๋กœ lambda๋ฅผ ํ™œ์šฉํ•ด์„œ ์กฐ๊ฑด์— ๋งž๊ฒŒ ์ •๋ ฌํ•ด์ฃผ๋Š” ๊ฒŒ ํ•ต์‹ฌ์ด๋‹ค.

 

<์ •๋‹ต์ฝ”๋“œ>

# 1. ์™„์ฃผํ•˜์ง€ ๋ชปํ•œ ์„ ์ˆ˜

def solution(participant, completion):
    answer = ''
    
    ans_dict = {}
    hash_val = 0
    
    for p in participant:
        ans_dict[hash(p)] = p
        hash_val += hash(p)
    
    for c in completion:
        hash_val -= hash(c)

    answer = ans_dict[hash_val]

    return answer

 

# 2. ํฐ์ผ“๋ชฌ

def solution(nums):
    N = len(nums)
    nums_set = set(nums)
    
    answer = min(N // 2, len(nums_set))
    
    return answer

 

# 3. ์ „ํ™”๋ฒˆํ˜ธ ๋ชฉ๋ก

def solution(phone_book):
    answer = True
    phone_book.sort()
    
    for i in range(len(phone_book) - 1):
        if phone_book[i] == phone_book[i + 1][:len(phone_book[i])]:
            answer = False
            break
            
    return answer

 

# 4. ์œ„์žฅ

from collections import defaultdict

def solution(clothes):
    clothes_dict = defaultdict(int)
    
    for c in clothes:
        clothes_dict[c[1]] += 1
    
    answer = 1
    
    for type in clothes_dict:
        answer *= (clothes_dict[type] + 1)
    
    answer -= 1
    
    return answer

 

# 5. ๋ฒ ์ŠคํŠธ ์•จ๋ฒ”

from collections import defaultdict

def solution(genres, plays):
    genre_play = defaultdict(int)
    
    for i in range(len(genres)):
        genre_play[genres[i]] += plays[i] 
    
    genres = list(enumerate(genres))
    temp = list(zip(genres, plays))
    
    temp.sort(key = lambda x : x[0][0])
    temp.sort(key = lambda x:(genre_play[x[0][1]], x[1]), reverse=True)
    
    genre_count = defaultdict(int)
    answer = []
    
    for (info, play) in temp:
        if genre_count[info[1]] >= 2:
            continue
            
        answer.append(info[0])
        genre_count[info[1]] += 1

        
    return answer

๋Œ“๊ธ€