본문으로 바로가기

[JAVA]N^2 배열 자르기

category 카테고리 없음 2022. 9. 17. 23:25

https://school.programmers.co.kr/learn/courses/30/lessons/87390

 

프로그래머스

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

programmers.co.kr

 

* 문제를 설명하자면 쉽게 말해

   주어진 규칙으로 2차원 배열을 만든 후  순서대로 1차원 배열에 left 에서 right까지 담아내는 것이다.

   혼자서 충분히 풀 수 있을 거라 생각했는데,,,

import java.util.*;

class Solution {
    public int[] solution(int n, long left, long right) {
        
        int[][] arr = new int[n][n];
        boolean[][] chk = new boolean[n][n];
        int num = 1;
        while(num <= n){
            for(int i = 0; i < num; i++){
                for(int j = 0; j < num; j++){
                    if(!chk[i][j]) {
                        chk[i][j] = true;
                        arr[i][j] = num;
                    }
                }
            }
            num++;
        }
        
        
        int[] answer = new int[(int)(right-left+1)];
        long cnt = 0;
        int count = 0;
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){                
                if(cnt>= left && cnt <= right){
                    answer[count] = arr[i][j];
                    count++;
                } else if(cnt > right) break;
                cnt++;
            }
        }
  
        return answer;
    }
}

 

 

처참한 정확성 테스트 결과,,,

 

답안을 보고 다니 너무나도 간결하게 풀었다.

단순하게 1차원배열로 만들었을때 규칙을 찾아내면 된다.

ex) index  0 1 2 3 / 4 5 6 7 / 8 9 10 11 / 12 13 14 15

                1 2 3 4 / 2 2 3 4 / 3 3   3   4 / 4   4    4   4

[풀이]

class Solution {
    public int[] solution(int n, long left, long right) {
    	int size = (int) (right - left) + 1;
        int[] answer = new int[size];

        // 조건 : target / n < target % n ->  (target % n) + 1;
        // 조건 : target / n >= target % n -> (target / n + 1)

        int loop  = 0;
        for(long target = left; target <= right; target++) {
            long rowIdx = target / n;
            long colIdx = target % n;
            if(rowIdx < colIdx) answer[loop] = (int) colIdx + 1;
            else answer[loop] = (int) rowIdx  + 1;
            loop++;
        }
        return answer;
    }
}