[큐/스택] 탑

정은경·2020년 4월 3일
0

1. 문제


2. 나의 풀이

def solution(heights):
    limit = len(heights)
    answer = []
    mem = []
    while heights:
        target = heights.pop()
        print("target :", target, end="")
        print("/ heights: ", heights)

        flag = 1
        while heights:
            temp = heights.pop()
            mem.append(temp)

            if temp > target:
                answer.append(len(heights)+1)
                heights += mem[::-1]
                mem = []
                flag = 0
                break
        heights += mem[::-1]
        mem = []
        if flag:
            answer.append(0)

    return answer[::-1]

heights = [1,5,3,6,7,6,5]

print(solution(heights))

3. 남의 풀이

def solution(heights):
    answer = []
    # 1. 스택 생성
    st = []
    
    # 2. heights 계산
    while heights:
        # 1. 맨 뒤 송신탑 꺼내옴.
        top = heights.pop()
        
        # 2. 현재 송신탑보다, 큰 송신탑이 나타날때까지 스택에 저장.
        while heights and heights[-1] <= top:
            st.append(heights.pop())
        
        # 3. 남아있는 길이를 asnwer에 저장
        answer.append(len(heights))
        
        # 4. 스택에 저장된 송신탑들을 다시 heights로 돌림
        while st:
            heights.append(st.pop())
    
    # 3. answer 역순으로 변환
    answer = answer[::-1]
    return answer




Reference

느낀 점

  • 처음에 문제를 보았을 때 문제조차 이해가 안되서 어떻게 푸는 거야라고 생각했었던 문제
  • 스택의 top과 나머지를 비교하는 문제
profile
#의식의흐름 #순간순간 #생각의스냅샷

0개의 댓글