[알고리즘문제풀기] n개 간격의 원소들

silver's avatar
Mar 04, 2025
[알고리즘문제풀기] n개 간격의 원소들

문제

내가 작성한 정답

1. Array이용

class Solution { public int[] solution(int[] num_list, int n) { int length = num_list.length%n==0?num_list.length/n:(num_list.length/n)+1; int[] answer = new int[length]; int index = 0; for(int i =0; i<num_list.length; i+=n){ answer[index++] = num_list[i]; } return answer; } }

2. ArrayList이용

import java.util.*; class Solution { public int[] solution(int[] num_list, int n) { List<Integer> answer = new ArrayList<>(); for(int i=0;i<num_list.length; i+=n){ answer.add(num_list[i]); } int[] answer1 = new int[answer.size()]; for(int i=0;i<answer.size(); i++){ answer1[i] = answer.get(i); } return answer1; } }
import java.util.*; class Solution { public int[] solution(int[] num_list, int n) { List<Integer> answer = new ArrayList<>(); for(int i=0;i<num_list.length; i+=n){ answer.add(num_list[i]); } return answer.stream().mapToInt(Integer::intValue).toArray(); } }

3. StreamAPI이용

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

다른 사람들의 정답

class Solution { public int[] solution(int[] num_list, int n) { Double length = Math.ceil(num_list.length/(n*1.0)); int[] answer = new int[length.intValue()]; for(int idx=0; idx<length; idx++) { answer[idx] = num_list[idx*n]; } return answer; } }
💡
Math.ceil : 주어진 숫자보다 크거나 같은 가장 작은 정수를 반환하는 메서드 Math.ceil은 항상 double 타입의 값을 반환하기 때문에 필요에 따라 정수형으로 변환해야 한다.
double number1 = 5.3; double number2 = -2.7; // Math.ceil 사용 double result1 = Math.ceil(number1); // 6.0 double result2 = Math.ceil(number2); // -2.0
Share article

silver