본문 바로가기
알고리즘 문제풀이/프로그래머스 Lv2

프로그래머스 LV2

by summer_light 2023. 9. 7.

# 가장 중요한 것: 변수에 내가 원하는 값이 제대로 들어가고 있는지 먼저 테스트하는 것. 
# 이 부분을 빨리 캐치하지 못하면 로직을 제대로 짜고도 '왜 안나오지'만 반복하게 된다. 
from collections import deque
def solution(q1, q2):
    #
    if (sum(q1) + sum(q2)) % 2  != 0:
        return -1 
    if sum(q1) == sum(q2) :
        return 0
    
    # 
    n = len(q1)
    q1 = deque(q1)
    q2 = deque(q2)
    sum1 = sum(q1)
    sum2 = sum(q2)
    
    cnt = 0
    while sum1 != sum2: 
        if cnt >= 4*n:
            return -1
        if sum1 < sum2:
            v = q2.popleft()
            q1.append(v)
            sum1 += v
            sum2 -= v
        elif sum1 > sum2:
            v = q1.popleft()
            q2.append(v)
            sum1 -= v
            sum2 += v
        cnt += 1
    
    return cnt

 

# 내 풀이 (시간 초과)
def solution(seq, k):
    n = len(seq)
    s = n - 1
    e = n
    while True:
        while sum(seq[s:e]) < k:
            s -= 1
        if sum(seq[s:e]) == k:
            if seq[e - 1] * (e - s) == k:
                s, e = seq.index(seq[e - 1]), seq.index(seq[e - 1]) + (e - s)
            break
        else:
            e -= 1

    return [s, e - 1]

# 내 풀이2 (시간 초과): sum(seq[s:e]) 때문에 불필요하게 리스트를 돌면서 부분합을 구하게 됨, 차이가 나는 원소 값만 계산하면 되는데.. 
def solution(seq, k):
    n = len(seq)
    s = n-1
    e = n
    sumSeq = seq[s]
    while True:
        while sumSeq < k:
            s -= 1
            sumSeq += seq[s]
        if sumSeq == k:
            if seq[e-1]*(e-s) == k:
                while s>=1 and seq[s] == seq[s-1]:
                    s-=1
                    e-=1
            break
        else: 
            e -= 1
            s = e-1
            sumSeq = seq[s]

    return [s, e-1]

# 내 풀이3 (통과): s는 초기화할 필요가 없었는데 이 때문에 불필요한 부분을 계속 체크해서 시간초과 발생 
# 연속된 부분 수열의 합: 투 포인터 생각
def solution(seq, k):
    n = len(seq)
    s = n-1
    e = n
    sumSeq = seq[s]
    while True:
        while sumSeq < k:
            s -= 1
            sumSeq += seq[s]
        if sumSeq == k:
            if seq[e-1]*(e-s) == k:
                while s>=1 and seq[s] == seq[s-1]:
                    s-=1
                    e-=1
            break
        else:
            e -= 1
            sumSeq -= seq[e]
    return [s, e-1]

# 내 풀이 : 성공, Counter, combinations 사용
from itertools import combinations as comb
from collections import Counter
def solution(orders, course):
    result = []
    for n in course:
        lst = []
        for order in orders:
            order = [x for x in order]
            for c in comb(order,n):
                s = ''.join(sorted(c))
                lst.append(s)
        dic = Counter(lst).most_common()
        if dic and dic[0][1] != 1:
            result += [d[0] for d in dic if d[1]==dic[0][1]]
    return sorted(result)

# 참고풀이 : 형태는 다르지만 나와 같은 로직의 풀이였다.
import collections
import itertools

def solution(orders, course):
    result = []

    for course_size in course:
        order_combinations = []
        for order in orders:
            order_combinations += itertools.combinations(sorted(order), course_size)

        most_ordered = collections.Counter(order_combinations).most_common()
        result += [ k for k, v in most_ordered if v > 1 and v == most_ordered[0][1] ]

    return [ ''.join(v) for v in sorted(result) ]

# 내 풀이 (런타임 에러)
food = 0
def solution(maps):
    global food
    dx = [-1, 1, 0, 0]
    dy = [0, 0, -1, 1]

    def dfs(x, y):
        global food
        if not visited[x][y] and graph[x][y] != 'X':
            food += int(graph[x][y])
            visited[x][y] = 1
            for i in range(4):
                nx = x + dx[i]
                ny = y + dy[i]
                if 0 <= nx < n and 0 <= ny < m:
                    dfs(nx, ny)

    answer = []
    graph = [[x for x in m] for m in maps]
    n = len(graph)
    m = len(graph[0])
    visited = [[0 for x in m] for m in maps]

    # dfs
    for i in range(len(graph)):
        for j in range(len(graph[0])):
            food = 0
            dfs(i, j)
            if food != 0:
                answer.append(food)
    return sorted(answer) or [-1]

# 내 풀이2: 재귀 문제는 최대 깊이 제한 꼭 풀어주자. 파이썬은 최대 깊이가 1000이라 10^6까지 풀어주는 게 좋다.
import sys
limit_number = 10000
sys.setrecursionlimit(limit_number)
food = 0

def solution(maps):
    global food
    dx = [-1, 1, 0, 0]
    dy = [0, 0, -1, 1]

    def dfs(x, y):
        global food
        if not visited[x][y] and graph[x][y] != 'X':
            food += int(graph[x][y])
            visited[x][y] = 1
            for i in range(4):
                nx = x + dx[i]
                ny = y + dy[i]
                if 0 <= nx < n and 0 <= ny < m:
                    dfs(nx, ny)

    answer = []
    graph = [[x for x in m] for m in maps]
    n = len(graph)
    m = len(graph[0])
    visited = [[0 for x in m] for m in maps]

    # dfs
    for i in range(len(graph)):
        for j in range(len(graph[0])):
            food = 0
            dfs(i, j)
            if food != 0:
                answer.append(food)
    return sorted(answer) or [-1]

# 내 풀이 : 실패 (86.7) // return '(None)' 을 한 줄 때문에. 해당 하는 값이 없으면 (None)출력 하는 걸 깜박함
def change(music):
    temp = ''
    for i,x in enumerate(music):
        if x == '#':
            s = temp[-1]
            temp = temp[:-1]
            temp += s.lower()
        else:
            temp += x
    return temp

def play(time, music):
    music = change(music)
    length = len(music)
    if time>length:
        answer = music*(time//length)
        answer += music[:time%length]
    else:
        answer = music[:time]
    return answer

def timeDiff(tA, tB):
    return int(tB[0:2])*60+int(tB[3:5]) - (int(tA[0:2])*60+int(tA[3:5]))

def solution(m, musicinfos):
    m = change(m)

    musicinfos = [[i+1]+list(musicinfo.split(',')) for i, musicinfo in enumerate(musicinfos)]
    musicinfos = [[x[0], timeDiff(x[1], x[2]), x[3], play(timeDiff(x[1],x[2]), x[4])] for x in musicinfos]
    musicinfos = sorted(musicinfos, key = lambda x: (-x[1], x[0]))

    for musicinfo in musicinfos:
        if m in musicinfo[3]:
            return musicinfo[2]

# 내 풀이2 : 성공 //
def change(music):
    temp = ''
    for i,x in enumerate(music):
        if x == '#':
            s = temp[-1]
            temp = temp[:-1]
            temp += s.lower()
        else:
            temp += x
    return temp

def play(time, music):
    music = change(music)
    length = len(music)
    if time>length:
        answer = music*(time//length)
        answer += music[:time%length]
    else:
        answer = music[:time]
    return answer

def timeDiff(tA, tB):
    return int(tB[0:2])*60+int(tB[3:5]) - (int(tA[0:2])*60+int(tA[3:5]))

def solution(m, musicinfos):
    m = change(m)

    musicinfos = [[i+1]+list(musicinfo.split(',')) for i, musicinfo in enumerate(musicinfos)]
    musicinfos = [[x[0], timeDiff(x[1], x[2]), x[3], play(timeDiff(x[1],x[2]), x[4])] for x in musicinfos]
    musicinfos = sorted(musicinfos, key = lambda x: (-x[1], x[0]))

    for musicinfo in musicinfos:
        if m in musicinfo[3]:
            return musicinfo[2]
    return '(None)'

# 참고 풀이
def shap_to_lower(s):
    s = s.replace('C#','c').replace('D#','d').replace('F#','f').replace('G#','g').replace('A#','a')
    return s

def solution(m,musicinfos):
    answer=[0,'(None)']   # time_len, title
    m = shap_to_lower(m)
    for info in musicinfos:
        split_info = info.split(',')
        time_length = (int(split_info[1][:2])-int(split_info[0][:2]))*60+int(split_info[1][-2:])-int(split_info[0][-2:])
        title = split_info[2]
        part_notes = shap_to_lower(split_info[-1])
        full_notes = part_notes*(time_length//len(part_notes))+part_notes[:time_length%len(part_notes)]
        if m in full_notes and time_length>answer[0]:
            answer=[time_length,title]
    return answer[-1]

댓글