매일 Algorithm

신재원·2023년 1월 16일
0

Algorithm

목록 보기
8/243

프로그래머스 : 소인수 분해 (LEVEL 0)

import java.util.*;
class Solution {
    public int[] solution(int n) {

        List<Integer> result= new ArrayList<>();

        for (int i = 2; i <= n; i++) {
            while(n % i == 0){
                n /= i;
                result.add(i);
            }
        }
        // Set 컬렉션을 사용해 list의 중복을 제거.
        Set<Integer> check = new HashSet<>(result);
        List<Integer> solution = new ArrayList<>(check);
        
        // 문제에 요구사항이 오름차순으로 정렬 이였음으로 오름차순 정렬.
        Collections.sort(solution);
        
        // List를 int 배열로 변환.
        int[] answer = solution.stream()
                .mapToInt(j -> j)
                .toArray();

        return answer;
    }


}

0개의 댓글