[프로그래머스/완전탐색] Level 2 카펫 (JAVA)

Jiwoo Kim·2021년 3월 3일
0

알고리즘 정복하기

목록 보기
29/85
post-thumbnail

문제


1차 풀이 (2021.03.03)

  1. 주어진 yellow에 따라 yellowHeightyellowWidth를 증감시키면서 정답 크기를 찾는다.
  2. brownGuessyellowGuess가 주어진 brownyellow와 같은 경우가 정답이므로, 이를 배열로 만들어 리턴한다.

코드

class Solution {
    public int[] solution(int brown, int yellow) {
        int yellowHeight = 1, yellowWidth = yellow / yellowHeight;
        while (true) {
            int brownGuess = (yellowWidth + 2) * 2 + yellowHeight * 2;
            int yellowGuess = yellowWidth * yellowHeight;
            if (brown == brownGuess && yellowGuess == yellow)
                break;
            yellowHeight++;
            yellowWidth = yellow / yellowHeight;
        }
        return new int[]{yellowWidth + 2, yellowHeight + 2};
    }
}

2차 풀이 (2021.08.27)

코드

class Solution {
    public int[] solution(int brown, int yellow) {
        int total = brown + yellow;
        
        for (int yellowHeight=1 ; yellowHeight<=Math.sqrt(yellow) ; yellowHeight++) {
            if (yellow % yellowHeight == 0) {
                int totalHeight = yellowHeight + 2;
                int totalWidth = (yellow / yellowHeight) + 2;
                
                if ((totalHeight * totalWidth) == total) {
                    return new int[]{totalWidth, totalHeight};
                }
            }
        }
        return null;
    }
}

0개의 댓글