본문 바로가기
알고리즘 배우기

[프로그래머스] Lv 1. 개인정보 수집 유효기간

by cwin 2024. 6. 30.

 

1. 나의 풀이 (개월 수가 기준이 이므로 정직하게 개월 수로 계산한 풀이)

def time_diff(today, privacies):
    diffs = []
    t_year, t_month, t_day = map(int, today.split('.'))
    for pri in privacies:
        p_type = pri[-1] # 약관 유형
        pri = pri[:-2]   # 약관 시작 날짜
        p_year, p_month, p_day = map(int, pri.split('.'))

        diff = ((t_year - p_year) * 12) + (t_month - p_month)
        # 만약 day가 지나지 않았다면, 개월 수 -1을 해줘야 한다.
        if t_day < p_day: 
            diff -= 1
        diffs.append([diff, p_type])
    print(diffs)
    return diffs

def solution(today, terms, privacies):
    answer = []
    table = {}
    for term in terms:
        type, period = term.split(' ')
        table[type] = int(period)
    diff = time_diff(today, privacies)
    
    for i, ele in enumerate(diff):
        type = ele[1]
        dif = ele[0]
        if table[type] <= dif:
            answer.append(i+1)
            

    return answer

위 풀이는 총 3번의 for문이 존재한다. 

def time_diff에서 privacies를 받아서 '현재까지의 개월 수'를 privacies 배열 길이 만큼 새로운 배열로 전처리하여 전달하기 때문이다.

1. terms 순회

2. privacies 순회

위 두 번의 순회는 필수이고, time_diff를 그냥 하나의 함수로 합치면 시간 복잡도가 약간은 줄어들 수 있다.

O(terms + privacies x 2) --> O(terms + privacies)

 

 

2. 일 수로 치환하여 계산하는 풀이 (출처 : 다른 사람 풀이)

def to_days(date):
    year, month, day = map(int, date.split("."))
    return year * 28 * 12 + month * 28 + day

def solution(today, terms, privacies):
    months = {v[0]: int(v[2:]) * 28 for v in terms}
    today = to_days(today)
    expire = [
        i + 1 for i, privacy in enumerate(privacies)
        if to_days(privacy[:-2]) + months[privacy[-1]] <= today
    ]
    return expire