[JAVA 문제 풀이] 154. n개 간격의 원소들

프로그래머스 (181889)
Stupefyee's avatar
Mar 24, 2025
[JAVA 문제 풀이] 154. n개 간격의 원소들
notion image
 

내가 작성한 코드

import java.util.stream.IntStream; class Solution { public int[] solution(int[] num_list, int n) { int[] answer = IntStream.iterate(0, i -> i < num_list.length, i -> i + n) // n만큼 인덱스를 증가시키는 스트림 생성 .map(i -> num_list[i]) .toArray(); return answer; } }
 

다른 사람의 코드

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]; // n만큼 증가 시키는 반복문 for (int i = 0; i < num_list.length; i += n) answer[idx++] = num_list[i]; return answer; } }
 
Share article

stupefyee