
* 문제 풀이
class Solution {
public int[] solution(int[] num_list, int n) {
int cnt = 0;
for(int i = 0; i < num_list.length; i++){
if(i % n == 0){
cnt++;
}
}
int[] answer = new int[cnt];
int index = 0;
for(int i = 0; i < num_list.length; i++){
if(i % n == 0){
answer[index++] = num_list[i];
}
}
return answer;
}
}
cnt 변수를 사용해 num_list 배열에서 인덱스 i가 n의 배수인 개수를 세어 새로운 배열의 크기를 정한다.
int[] answer = new int[cnt]; cnt 개수만큼 크기를 가진 Int[] answer 배열을 생성
int index = 0; index 변수를 선언하여 배열에 값을 저장.
for 문을 통해 num_list의 배열요소를 확인.
조건문 i%n = 0 를 만족하는 경우 answer 배열에 추가.
index++을 통해 값을 저장한 후 다음 인덱스로 이동.
* 프로그래머스 다른 풀이
class Solution {
public int[] solution(int[] num_list, int n) {
int N = num_list.length % n == 0 ? num_list.length / n : num_list.length / n + 1;
int idx = 0;
int[] answer = new int[N];
for (int i = 0;i < num_list.length;i+=n)
answer[idx++] = num_list[i];
return answer;
}
}
import java.util.ArrayList;
class Solution {
public int[] solution(int[] num_list, int n) {
ArrayList<Integer> list = new ArrayList();
for (int i = 0; i < num_list.length;) {
list.add(num_list[i]);
i+=n;
}
int[] answer = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
answer[i] = list.get(i);
}
return answer;
}
}
'코테 > 프로그래머스 JAVA Lv.0' 카테고리의 다른 글
| [프로그래머스/java/Lv.0] n 번째 원소까지 (0) | 2025.02.19 |
|---|---|
| [프로그래머스/java/Lv.0] n 번째 원소부터 (0) | 2025.02.18 |
| [프로그래머스/java/Lv.0] 홀수 vs 짝수 (0) | 2025.02.15 |
| [프로그래머스/java/Lv.0] 5명씩 (0) | 2025.02.14 |
| [프로그래머스/java/Lv.0] 할 일 목록 (0) | 2025.02.13 |