[월간 코드 챌린지 시즌3] n^2 배열 자르기
[월간 코드 챌린지 시즌3] n^2 배열 자르기
🙋♂️ 들어가며
이번 문제는 수학적 사고가 필요한 문제였다.
우선 내가 생각한 방법은 다음과 같다.
접근 방법
n = 5 가정
| 1 | 2 | 3 | 4 | 5 |
| 2 | 2 | 3 | 4 | 5 |
| 3 | 3 | 3 | 4 | 5 |
| 4 | 4 | 4 | 4 | 5 |
| 5 | 5 | 5 | 5 | 5 |
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.

