You will be fine

1. 크레인 인형뽑기 (프로그래머스)

by BFine
반응형

가. 문제파악

 1. 유형 : Stack & 구현

    -  level1 문제인데 오랜만에 해서 그런지 시간도 오래걸리고 놓치는 부분이 많이있었다. 

    -  무턱대고 코드부터 작성하다보면 수정의 늪에 빠지기 쉽다...

 

나. 코드 

 1. 풀이 : Stack을 세로로 구현

    -  통과는 했지만 좋은 풀이 방법은 아닌 것 같다.

    -  최대 30까지 가능해서 세로 한줄당 하나의 스택으로해서 풀었다.

public int solution(int[][] board, int[] moves) {

        int answer = 0;

        int n = board.length;

        Stack<Integer>[] stacks = new Stack[n];
        Stack<Integer> result = new Stack<>();

        for (int i = 0; i < stacks.length; i++) {
            stacks[i] = new Stack<>();
        }

        for (int i = 0; i < n; i++) {
            for(int j = n-1; j >=0; j--){
            // 거꾸로 push 해야함
                if(board[j][i] != 0){
                    stacks[i].push(board[j][i]);
                }
            }
        }

        for (int i = 0; i < moves.length; i++) {
            if(!stacks[moves[i]-1].isEmpty()){
                try {
                    if(result.isEmpty()){
                        result.add(stacks[moves[i]-1].pop());
                        continue;
                    }

                    if(result.peek() == stacks[moves[i]-1].peek()){
                        stacks[moves[i]-1].pop();
                        result.pop();
                        answer++;
                    }else{
                        result.add(stacks[moves[i]-1].pop());
                    }

                }catch (Exception e){

                }
            }
        }
        return answer*2;
    }

 

 2. 풀이 : 배열을 활용하자!

    -  위의 풀이의 문제는 최대치가 컷다면 메모리 문제가 발생할 것이다.

    -  단순히 배열을 탐색해서 풀자, 해당라인을 세로로 쭉 탐색해서 풀면 간단하다.

  public int solution(int[][] board, int[] moves) {

        int answer = 0;

        int n = board.length;

        Stack<Integer> result = new Stack<>();

        for (int i = 0; i < moves.length; i++) {
            int location = moves[i]-1;
            for (int k = 0; k < board.length; k++) {
                if(board[k][location] != 0){
                    if(result.isEmpty()){
                        result.add(board[k][location]);
                        board[k][location] = 0;
                        break; // 아래 peek()의 exception 방지
                    }

                    if(result.peek() == board[k][location]){
                        result.pop();
                        answer++;
                    }else{
                        result.add(board[k][location]);
                    }
                    
                    board[k][location] = 0;
                    break;
                }
            }
        }
        return answer*2;
    }
  }
반응형

블로그의 정보

57개월 BackEnd

BFine

활동하기