[알고리즘문제풀기] n 번째 원소까지

silver's avatar
Mar 05, 2025
[알고리즘문제풀기] n 번째 원소까지

문제

내가 작성한 정답

1. ArrayList이용

class Solution { public int[] solution(int[] num_list, int n) { int[] answer = new int[n]; for(int i=0; i<n; i++){ answer[i] = num_list[i]; } return answer; } }

2. StreamAPI이용

import java.util.stream.*; class Solution { public int[] solution(int[] num_list, int n) { return IntStream.range(0,n) .map(i->num_list[i]) .toArray(); } }

다른 사람들의 정답

1. Array이용

import java.util.*; class Solution { public int[] solution(int[] num_list, int n) { int[] answer = {}; answer = Arrays.copyOfRange(num_list,0,n); return answer; } }
💡
public static int[] copyOfRange(int[] original, int from, int to)
: Java에서 배열의 특정 범위를 복사하여 새로운 배열을 생성하는 메서드로 java.util.Arrays 클래스에 포함

2. StreamAPI이용

import java.util.*; class Solution { public Integer[] solution(int[] numList, int n) { // Arrays.stream(numList): numList 배열을 스트림으로 변환 // .boxed(): 기본형 int를 Integer 객체로 변환 // .limit(n): 스트림의 요소 수를 n으로 제한 // .toArray(Integer[]::new): 제한된 스트림을 Integer 배열로 변환 return Arrays.stream(numList) // numList 배열을 스트림으로 변환 .boxed() // 기본형 int를 Integer 객체로 변환 .limit(n) // 처음 n개의 요소만 선택 .toArray(Integer[]::new); // 선택된 요소를 Integer 배열로 변환하여 반환 } }
 
Share article

silver