Post

[월간 코드 챌린지 시즌3] n^2 배열 자르기

[월간 코드 챌린지 시즌3] n^2 배열 자르기

🙋‍♂️ 들어가며

이번 문제는 수학적 사고가 필요한 문제였다.

우선 내가 생각한 방법은 다음과 같다.

접근 방법

n = 5 가정

     
12345
22345
33345
44445
55555
1
2
3
4
5
6
7
left = 1
right = 7
 -> {2,3,4,5,2,2,3}

left = 15
right = 20
 -> {4,4,4,4,5,5}



n = 100,000

1
2
3
left = 99 9999 9996
right = 99 9999 9999
 -> {100000, 100000, 100000, 100000}



규칙을 발견할 수 있는데

left <= right

가 유지될 동안, mod 그리고 remainder를 통해 만들 수 있었다.

2가지 경우로 나뉘는데, mod >= remainder 일때 값을 mod + 1 로 처리

mod < remainder 일때는 값을 remainder + 1 로 처리하면 되겠다




✅ 코드

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
class Solution {
    public int[] solution(int n, long left, long right) {
        int[] arr = new int[(int) (right-left) + 1];
        
        int idx = 0;
        while (left <= right) {
            int mod = (int) (left / n);
            int remainder = (int) (left % n);
            
            if (mod < remainder) {
                arr[idx] = remainder + 1;
                left++;
                idx++;
            }
            else if (mod >= remainder) {
                arr[idx] = mod + 1;
                left++;
                idx++;
            }
        }

        
        
        return arr;
    }
}
This post is licensed under CC BY 4.0 by the author.
3D GIF

Trending Tags

도움이 필요하면
나를 눌러 구리🐻
챗봇
너굴
bot
어서와 구리 ʕ ·ᴥ·ʔ
무엇이 필요하셔 구리?

Trending Tags

도움이 필요하면
나를 눌러 구리🐻
챗봇
너굴
bot
어서와 구리 ʕ ·ᴥ·ʔ
무엇이 필요하셔 구리?