[JAVA 문제 풀이] 145. 리스트 자르기

프로그래머스 (181897)
Stupefyee's avatar
Mar 17, 2025
 [JAVA 문제 풀이] 145. 리스트 자르기
notion image
 

내가 작성한 코드

import java.util.stream.IntStream; class Solution { public int[] solution(int n, int[] slicer, int[] num_list) { int[] answer = null; switch (n) { case 1: answer = IntStream.range(0, slicer[1] + 1).map(i -> num_list[i]).toArray(); break; case 2: answer = IntStream.range(slicer[0], num_list.length).map(i -> num_list[i]).toArray(); break; case 3: answer = IntStream.range(slicer[0], slicer[1] + 1).map(i -> num_list[i]).toArray(); break; case 4: answer = IntStream.iterate(slicer[0], i -> i <= slicer[1], i -> i + slicer[2]) .map(i -> num_list[i]) .toArray(); break; } return answer; } }
  • IntStream.iterate: for문처럼 증감식 삽입 가능
 

다른 사람의 코드

class Solution { public int[] solution(int n, int[] slicer, int[] num_list) { // 시작 인덱스 설정: // - n이 1이면 전체 배열을 선택해야 하므로 0 // - 그 외에는 slicer[0] 사용 int start = n == 1 ? 0 : slicer[0]; // 종료 인덱스 설정: // - n이 2이면 배열의 끝까지 선택해야 하므로 num_list.length - 1 // - 그 외에는 slicer[1] 사용 int end = n == 2 ? num_list.length - 1 : slicer[1]; // 간격(step) 설정: // - n이 4일 경우 slicer[2] 사용 (주어진 간격만큼 건너뜀) // - 그 외에는 1씩 증가 int step = n == 4 ? slicer[2] : 1; // 결과 배열 크기 계산: // - (end - start + step) / step은 선택된 요소 개수를 의미 int[] answer = new int[(end - start + step) / step]; // 결과 배열에 값을 저장하는 반복문 // - i는 start부터 step씩 증가하며 end까지 순회 // - j는 결과 배열에 값을 채우는 인덱스 for (int i = start, j = 0; i <= end; i += step) { answer[j++] = num_list[i]; } // 최종 결과 반환 return answer; } }
 
Share article

stupefyee