알고리즘

프로그래머스 배열 만들기 (JAVA)

박카스마시며코딩 2023. 5. 8. 22:06

https://school.programmers.co.kr/learn/courses/30/lessons/181921

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

저는 BFS를 통해 문제를 해결하였습니다. 

l이 1보다 크기 때문에 0은 될 수 없어서 먼저 큐에 5를 넣어 진행하고 큐에 있는 값을 num이라 할 때

num * 10 , num * 10 + 5 이 두가지 경우를 보면 5와 0으로 된 모든 경우를 찾을 수 있고, 이 값이 r을 넘기면 더 진행하지 않도록 하여 문제를 해결하였습니다.

 

import java.util.*;

class Solution {
    public int[] solution(int l, int r) {
        int[] answer = cal(l,r);
        return answer;
    }
    private static int[] cal(int l,int r){
        List<Integer> result = new LinkedList<>();
        Queue<Integer> q = new LinkedList<>();
        q.offer(5);
        while(!q.isEmpty()){
            int num = q.poll();
            if(num >= l && num <= r){
                result.add(num);
            }
            if(num > r){
                continue;
            }
            q.offer(num * 10);
            q.offer(num * 10 + 5);
        }
        if(result.size() == 0){
            return new int[]{-1};
        }
        int[] temp = new int[result.size()];
        for(int i = 0 ; i < result.size() ; i++){
            temp[i] = result.get(i);
        }
        return temp;
    }
}