오늘 ONEUL
오늘의 개발
오늘 ONEUL
전체 방문자
오늘
어제
  • 오늘의 개발 (248)
    • 📝 TIL (121)
    • 💡 Projects (6)
      • 드로잉 게임 [눈치 코치 캐치!] (4)
      • 익명고민상담소 [대나무숲] (2)
    • 🌎 Web (47)
      • Spring (3)
      • Java (14)
      • JavaScript (16)
      • CSS (10)
      • HTML (4)
    • 📚 Database (7)
    • 👾 Trouble Shooting (3)
    • 📊 Algorithm&SQL (39)
    • 😺 Git (1)
    • 📖 Books (7)
      • 자바 객체 지향의 원리와 이해 (7)
    • 📁 ETC (2)
    • 되돌아보기 (15)

블로그 메뉴

  • 😺 Github
  • 🍀 NAVER Blog

인기 글

최근 댓글

최근 글

태그

  • 프로그래머스
  • 항해99
  • 자바
  • Algorithm
  • 자바스크립트
  • JavaScript
  • 알고리즘
  • Java
  • Til
  • MySQL

티스토리

hELLO · Designed By 정상우.
오늘 ONEUL

오늘의 개발

[Java/프로그래머스] 최소직사각형
📊 Algorithm&SQL

[Java/프로그래머스] 최소직사각형

2022. 11. 19. 19:00

문제

 

 

 

풀이

(1) 문제 분석하기

  • 문제에 현혹되지 말자. 결국 긴 변 중에 가장 긴 변과 짧은 변 중에 가장 긴 별을 곱하면 된다.
  • for문과 if문을 중첩으로 사용했더니 바로 시간초과가 나버렸다...!
    • 배열의 정렬을 이용해보자.
    • 최대수, 최소수를 구해주는 Math.max, Math.min을 이용해보자.

 

(2) 슈도코드 작성하기

// 첫번째 풀이
각 변을 담을 int 변수 biggerSideMax, smallerSideMax 선언
for(sizes의 길이만큼) {
	if(첫번째 요소가 두번째 요소보다 클 때) {
    	if(긴 변의 요소가 biggerSideMax 보다 클 때 {
        	biggerSideMax에 긴 변 요소 담기
        }
        if(짧은 변의 요소가 smallerSideMax보다 클 때) {
        	smallerSideMax에 짧은 변 요소 담기
        }
    } else {
    	긴 변과 짧은 변의 순서 바꿔주기
        i--
    }
}
biggerSideMax * smallerSideMax



// 두번째 풀이
긴 변이 담길 배열과 짧은 변이 담길 배열 선언
for(sizes의 길이만큼) {
	if(첫번째 요소가 두번째 요소보다 클 때) {
    	첫번째 요소를 긴 변 배열에 담기
        두번째 요소를 짧은 변 배열에 담기
    } else {
    	두번째 요소를 긴 변 배열에 담기
        첫번째 요소를 짧은 변 배열에 담기
    }
}
두 배열 모두 오름차순으로 정렬
각 배열의 마지막 요소만 출력
biggerSideMax * smallerSideMax



// 세번째 풀이
각 변을 담을 int 변수 biggerSideMax, smallerSideMax 선언
for(sizes의 길이만큼) {
	Math.max 메소드를 이용하여 긴 변을 구하고,
    Math.min 메소드를 이용하여 짧은 변을 구하기
}
biggerSideMax * smallerSideMax

 

 

(3) 코드 구현하기

 

시간초과 났던 첫번째 풀이

package algorithm.test14;

public class Solution {
    public static void main(String[] args) {
        int[][] arr = {{60, 50}, {30, 70}, {60, 30}, {80, 40}};
        System.out.println(solution(arr));
    }

    public static int solution(int[][] sizes) {
        // 긴 변중에 가장 긴 변
        // 짧은 변 중에 가장 긴 변

        // 첫번재 풀이
        int biggerSideMax = 0;
        int smallerSideMax = 0;
        for (int i = 0; i < sizes.length; i++) {
            if (sizes[i][0] > sizes[i][1]) {
                if (biggerSideMax < sizes[i][0]) {
                    biggerSideMax = sizes[i][0];
                }
                if (smallerSideMax < sizes[i][1]) {
                    smallerSideMax = sizes[i][1];
                }
            } else {
                int temp = sizes[i][0];
                sizes[i][0] = sizes[i][1];
                sizes[i][1] = temp;
                i--;
            }
        }
        return biggerSideMax * smallerSideMax;
    }
}

 

배열의 정렬을 이용한 두번째 풀이

package algorithm.test14;

import java.util.Arrays;

public class Solution {
    public static void main(String[] args) {
        int[][] arr = {{60, 50}, {30, 70}, {60, 30}, {80, 40}};
        System.out.println(solution(arr));
    }

    public static int solution(int[][] sizes) {
        // 긴 변중에 가장 긴 변
        // 짧은 변 중에 가장 긴 변

        // 두번째 풀이
        int[] firstArr = new int[sizes.length];
        int[] secondArr = new int[sizes.length];
        for (int i = 0; i < sizes.length; i++) {
            if (sizes[i][0] > sizes[i][1]) {
                firstArr[i] += sizes[i][0];
                secondArr[i] += sizes[i][1];
            } else {
                firstArr[i] += sizes[i][1];
                secondArr[i] += sizes[i][0];
            }
        }
        Arrays.sort(firstArr);
        Arrays.sort(secondArr);
        int biggerSideMax = firstArr[sizes.length - 1];
        int smallerSideMax = secondArr[sizes.length - 1];

        return biggerSideMax * smallerSideMax;
    }
}

 

Math.max, Math.min을 이용한 세번째 풀이

package algorithm.test14;

public class Solution {
    public static void main(String[] args) {
        int[][] arr = {{60, 50}, {30, 70}, {60, 30}, {80, 40}};
        System.out.println(solution(arr));
    }

    public static int solution(int[][] sizes) {
        // 긴 변중에 가장 긴 변
        // 짧은 변 중에 가장 긴 변

        // 세번째 풀이
        int biggerSideMax = 0, smallerSideMax = 0;
        for (int[] size : sizes) {
            biggerSideMax = Math.max(biggerSideMax, Math.max(size[0], size[1]));
            smallerSideMax = Math.max(smallerSideMax, Math.min(size[0], size[1]));
        }

        return biggerSideMax * smallerSideMax;
    }
}

 

 

 

 

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

저작자표시 비영리 변경금지 (새창열림)

'📊 Algorithm&SQL' 카테고리의 다른 글

[Java/프로그래머스] 두 개 뽑아서 더하기  (0) 2022.11.19
[Java/프로그래머스] 같은 숫자는 싫어  (0) 2022.11.19
[Java/프로그래머스] 3진법 뒤집기  (0) 2022.11.19
[Java/프로그래머스] 하샤드 수  (0) 2022.11.19
[Java/프로그래머스] 콜라츠 추측  (0) 2022.11.19
    오늘 ONEUL
    오늘 ONEUL
    Backend Engineer ㅣ 어제보다 나은 오늘, 재밌는 건 오늘부터!

    티스토리툴바