[프로그래머스] Level0. n의 배수 고르기

Benjamin·2023년 2월 9일
0

프로그래머스

목록 보기
14/58

내 풀이

import java.util.ArrayList;

class Solution {
    public int[] solution(int n, int[] numlist) {
        ArrayList<Integer> answerList = new ArrayList<>();
        for(int i=0; i<numlist.length; i++) {
            if(numlist[i]%n == 0) answerList.add(numlist[i]);
        }
        int[] answer = new int[answerList.size()];
        for(int i=0; i<answer.length; i++) {
            answer[i] = answerList.get(i);
        }
        return answer;
    }
}

항상 배열로 반환해야하는데, 배열은 처음에 사이즈를 지정해야하니 사이즈를 알 수 없어 List에 따로 담아 배열로 다시 옮기는작업해야할 때 번거로워진다.
리스트를 배열로 변환하는 toArray()가 있지만, List는 Integer타입으로 생성해야하고, 배열은 int타입이라 맞지않아 또 이걸 해결해야하는데, 복잡해져서 늘 반복문을 이용해 옮기고는한다.

다른 풀이를 보니 stream을 사용해 간략하게 해결했길래 이 부분은 유의해서 공부해두려한다.

다른 풀이

import java.util.Arrays;

class Solution {
    public int[] solution(int n, int[] numList) {
        return Arrays.stream(numList).filter(value -> value % n == 0).toArray();
    }
}

0개의 댓글