코딩테스트 연습 - 10주차

[[2, -1, 4], [-2, -1, 4], [0, -1, 1], [5, -8, -12], [5, 8, 12]] ["....*....", ".........", ".........", "*.......*", ".........", ".........", ".........", ".........", "*.......*"] [[0, 1, -1], [1, 0, -1], [1, 0, 1]] ["*.*"] [[1, -1, 0], [2, -1, 0], [4, -

programmers.co.kr

 

 

 


 

 

  • 풀이

 

 

친절하게 위와같은 설명이 있다. 위의 방식을 참고하여 구현했습니다.

 

반복문은 모든 선분끼리 교점이 있는지 없는지 반복작업 해주었습니다.

 

반복문을 돌면서 교점이 있는 경우 교점은 Set을 통해 저장해주었습니다.

(Set을 사용한 이유는 중복값을 체크해주지 않아도되고, 꺼내서 사용할 용도가 아닌 포함 여부만 판단할 것이기때문에 순서가 상관없어서 다른 Collection보다 빠르다.)

 

set에 저장하며 가장 왼쪽, 가장 오른쪽, 가장 위, 가장아래 index를 업데이트 시킵니다.

 

위의 반복문이 끝난 뒤, 가장 위 index부터 가장왼쪽index~가장오른쪽index의 반복을 가장 아래 index까지 반복하며 set에 있는 교점은 *를 추가, 교점이 없는 경우 .를 추가했습니다.

 

 

 

 

  • 코드

 

import java.util.*;

class Solution {
    public String[] solution(int[][] line) {
        int minC = Integer.MAX_VALUE;
        int minR = Integer.MAX_VALUE;
        int maxC = Integer.MIN_VALUE;
        int maxR = Integer.MIN_VALUE;
        // 위치 저장해줄 set함수
        Set<String> set = new HashSet<>();
        for(int i=0; i<line.length-1; i++) {
            for(int j=i+1; j<line.length; j++) {
                int temp = line[i][0]*line[j][1] - line[i][1]*line[j][0];
                int temp1 = line[i][1]*line[j][2] - line[i][2]*line[j][1];
                int temp2 = line[i][2]*line[j][0] - line[i][0]*line[j][2];
                if(temp == 0 || temp1%temp != 0 || temp2%temp != 0) 
                    continue;
                
                int x = temp1/temp;
                int y = temp2/temp;
                
                set.add(x+","+y);
                minR = Math.min(minR, x);
                minC = Math.min(minC, y);
                maxR = Math.max(maxR, x);
                maxC = Math.max(maxC, y);
            }
        }
        // 교점이 없는 경우
        if(minR == Integer.MAX_VALUE) {
            String[] answer = new String[1];
            answer[0] = "*";
            return answer;
        }
        
        // 위 맨 왼쪽 ~ 아래 맨 오른쪽까지
        String[] answer = new String[maxC-minC+1];
        int index = 0;
        for(int i = maxC; i >= minC; i--){
            StringBuilder sb = new StringBuilder();
            for(int j = minR; j <= maxR; j++){
                if(set.contains(j+","+i)){
                    sb.append("*");
                }
                else
                    sb.append(".");
            }
            answer[index++] = sb.toString(); 
        }
        return answer;
    }
}

+ Recent posts