문제 설명
정수 n, left, right가 주어집니다. 다음 과정을 거쳐서 1차원 배열을 만들고자 합니다.
n행 n열 크기의 비어있는 2차원 배열을 만듭니다.
i = 1, 2, 3, …, n에 대해서, 다음 과정을 반복합니다.
1행 1열부터 i행 i열까지의 영역 내의 모든 빈 칸을 숫자 i로 채웁니다.
1행, 2행, …, n행을 잘라내어 모두 이어붙인 새로운 1차원 배열을 만듭니다.
새로운 1차원 배열을 arr이라 할 때, arr[left], arr[left+1], …, arr[right]만 남기고 나머지는 지웁니다.
정수 n, left, right가 매개변수로 주어집니다. 주어진 과정대로 만들어진 1차원 배열을 return 하도록 solution 함수를 완성해주세요.
제한사항
1 ≤ n ≤ 107
0 ≤ left ≤ right < n2
right - left < 105
입출력 예
n left right result
3 2 5 [3,2,2,3]
4 7 14 [4,3,3,3,4,4,4,4]
======================================================================================================
import java.util.*;
class Solution {
public int[] solution(int n, long left, long right) {
//리턴할 배열의 크기는 left부터 right까지이며, left를 포함하기때문에 1을 더함
int[] answer = new int[(int)right-(int)left+1];
int index=0;
long temp=0;
left = left+1;
right = right+1;
for(long i=left;i<=right;i++){
if(i%n==0){ //i를n으로 나눴을때 나머지가 0이라면
temp=n; //temp 는 0
}else{ //나머지가 있다면
temp=i%n; //temp에는 나머지를 넣음
if(temp<=i/n){ //다만나머지가 i/n으로 나눈 몫보다 작거나 같다면
temp = i/n+1; //temp는 몫+1로 변경
}
}
answer[index]=(int)temp;
index++;
}
return answer;
} }
import java.util.*;
class Solution {
public int[] solution(int n, long left, long right) {
//리턴할 배열의 크기는 left부터 right까지이며, left를 포함하기때문에 1을 더함
int[] answer = new int[(int)right-(int)left+1];
int[][] twoDimensionalArray = new int[n][n] ;
int count=0;
int index=0;
//2차원 배열 생성
for(int i=0;i<twoDimensionalArray.length;i++){
for(int j=0;j<twoDimensionalArray.length;j++){
//해당입력의 규칙은 2차원배열의 index 중 큰수에+1을 하면 일치함
//ex) [0,2] [2,0] [2,1] [2,2] 에는 3이들어가고
//[1,0] [1,1] [0,1] 에는 2가 들어감
if(i>j){
twoDimensionalArray[i][j] = i+1;
}else if(j>i){
twoDimensionalArray[i][j] = j+1;
}else{
twoDimensionalArray[i][j] = i+1;
}
//count 가 left와 right 범위에 있다면, 바로전에 생성한 값을 리턴할 배열에 넣어줌
//index는 0부터 시작해서 아래의 if문을 탈때만 추가함
if(left<=count&& count<=right){
answer[index] = twoDimensionalArray[i][j];
index++;
}else{
// if(count>right){
// answer;
// }
}
//count 를 생성하여, 순차적으로 배열에 값을 넣을때마다 증가시킴
count++;
}
}
//출력테스트
for(int i=0;i<twoDimensionalArray.length;i++){
for(int j=0;j<twoDimensionalArray.length;j++){
System.out.print(twoDimensionalArray[i][j] + "");
}
System.out.println();
}
return answer;
} }