Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

코딩응급실

프로그래머스: n^2 배열 자르기 본문

Java

프로그래머스: n^2 배열 자르기

Daeryuk Kim 2024. 3. 7. 00:07
1 2 3
2 2 3
3 3 3

 

0          1           2         3          4            5         6         7          8

1 2 3 2 2 3 3 3 3
import java.util.*;

class Solution {
    public int[] solution(int n, long left, long right) {
        ArrayList<Integer> list = new ArrayList<>();
        
        // i는 범위의 시작점인 left에서 끝점인 right까지 변합니다.
        for (long i = left; i <= right; i++) {
            // i를 n으로 나눈 몫과 i를 n으로 나눈 나머지 중
            // 더 큰 값에 1을 더한 값을 리스트에 추가합니다. 
            // 이는 2차원 배열에서 각 칸에 채워지는 값을 계산하는 규칙을
            // 1차원 배열로 변환한 것입니다.
            list.add(Math.max((int)(i / n), (int)(i % n)) + 1);
        }
        
        int[] answer = new int[list.size()];
        // ArrayList의 모든 원소를 순회하며, 각 원소를 answer 배열에 복사합니다.
        for (int i = 0; i < list.size(); i++) {
            answer[i] = list.get(i);
        }
        
        return answer;
    }
    
    public static void main(String[] args) {
        int n = 3;
        int left = 2;
        int right = 5;
        
        Solution sol = new Solution();
        int[] result = sol.solution(n, left, right);
        System.out.println(Arrays.toString(result)); 
    }
}

'Java' 카테고리의 다른 글

프로그래머스: 행렬의 곱셈  (1) 2024.03.07
프로그래머스: H-index  (0) 2024.03.07
프로그래머스: 카펫  (1) 2024.03.06
프로그래머스: 할인행사  (1) 2024.03.06
프로그래머스: 괄호 회전하기  (1) 2024.03.06