ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [프로그래머스] 탑
    Algorithm 2020. 9. 15. 12:27
    반응형

    문제 설명

    수평 직선에 탑 N대를 세웠습니다. 모든 탑의 꼭대기에는 신호를 송/수신하는 장치를 설치했습니다. 발사한 신호는 신호를 보낸 탑보다 높은 탑에서만 수신합니다. 또한, 한 번 수신된 신호는 다른 탑으로 송신되지 않습니다.

    예를 들어 높이가 6, 9, 5, 7, 4인 다섯 탑이 왼쪽으로 동시에 레이저 신호를 발사합니다. 그러면, 탑은 다음과 같이 신호를 주고받습니다. 높이가 4인 다섯 번째 탑에서 발사한 신호는 높이가 7인 네 번째 탑이 수신하고, 높이가 7인 네 번째 탑의 신호는 높이가 9인 두 번째 탑이, 높이가 5인 세 번째 탑의 신호도 높이가 9인 두 번째 탑이 수신합니다. 높이가 9인 두 번째 탑과 높이가 6인 첫 번째 탑이 보낸 레이저 신호는 어떤 탑에서도 수신할 수 없습니다.

    public class Top {
        static Stack<Integer> top = new Stack<>();
        static Stack<Integer> save = new Stack<>();
    
        public static void main(String[] args) {
            System.out.println(Arrays.toString(solution(new int[]{1, 5, 3, 6, 7, 6, 5})));
        }
    
        static public int[] solution(int[] heights) {
            int[] answer = new int[heights.length];
            int popNumber;
            for (int height : heights) {
                top.push(height);
            }
            for (int i = 0; i < heights.length; i++) {
                popNumber = top.pop();
                answer[heights.length - i - 1] = check(popNumber, top, top.size());
                for (int k = 0; k < save.size();) {
                    top.push(save.pop());
                    System.out.println("save: " + save+"top: "+ top);
                }
            }
            return answer;
        }
    
        public static int check(int popNumber, Stack<Integer> top, int index) {
            if (index < 0 || top.isEmpty())
                return 0;
            if (top.peek() > popNumber) {
                return index;
            } else {
                save.push(top.pop());
                return check(popNumber, top, index - 1);
            }
        }
    }

    Stack 과 재귀호출로 풀이

    반응형

    'Algorithm' 카테고리의 다른 글

    [프로그래머스] 크레인인형뽑기게임  (0) 2020.09.15
    [프로그래머스] 타겟 넘버  (0) 2020.09.15
    [프로그래머스] 스킬 트리  (0) 2020.09.15
    [프로그래머스] 소수 만들기  (0) 2020.09.15
    [프로그래머스] 캐시  (0) 2020.09.15

    댓글

Designed by Tistory.