알고리즘/프로그래머스

[프로그래머스]JAVA - Level2. 기능 개발

K.두부 2022. 8. 30. 19:49
반응형

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

 

프로그래머스

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

programmers.co.kr

풀이

세상에 중간 단계의 알고리즘은 없는 걸까? 체감상 순한맛, 매운맛밖에 없는 것 같다..

이번 알고리즘 문제는 배열로만 해결할 수도 있고, Queue를 이용해서 해결해도 된다. 문제에서 요구하는 건 Queue로 해결하는 방법이기 때문에 Queue를 이용해서 풀어봤다.

 

우선 progresses 와 speeds 를 이용해서 배포가 가능한 날짜를 구해서 Queue에 넣어줘야 한다.  배포가 가능한 날짜를 구하는 공식은 아래와 같다.

// 배포 가능한 날짜 구하기
for (int i=0; i<progresses.length; i++) {
    day = (100 - progresses[i]) % speeds[i] > 0 ? ((100 - progresses[i]) / speeds[i]) +1 : (100 - progresses[i]) / speeds[i];
    que.add(day);
}

작업 완료 (100) 에서 현재 작업 진도 (progresses) 를 뺀 후에 작업 속도 (speeds) 를 나눠주면 된다. 여기서 중요한 건 int형 타입으로인한 오류인데 나머지 값의 유무로 쉽게 해결할 수 있다. 나머지가 0보다 크다면 +1을 시켜주면 된다.

 

<최종코드>

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

class Solution {
    public int[] solution(int[] progresses, int[] speeds) {
        int day = 0; // 배포 가능한 날짜 변수
        
        Queue<Integer> que = new LinkedList<Integer>();
        
        // 배포 가능한 날짜 구하기
        for (int i=0; i<progresses.length; i++) {
            day = (100 - progresses[i]) % speeds[i] > 0 ? ((100 - progresses[i]) / speeds[i]) +1 : (100 - progresses[i]) / speeds[i];
            que.add(day);
        }
        
        ArrayList<Integer> arr = new ArrayList<>();
        
        int cnt = 1;
        int now_day = que.poll();
        while (!que.isEmpty()) {
            int next_day = que.poll();
            
            // 다음 작업이 배포까지 더 오래걸릴 경우 cnt 초기화
            if (next_day > now_day) {
                arr.add(cnt);
                now_day = next_day;
                cnt = 1;
            } else {
                cnt++;
            }
        }
        
        arr.add(cnt); // 마지막 처리
        int[] answer = new int[arr.size()];
        
        for (int i=0; i<arr.size(); i++) {
            answer[i] = arr.get(i);    
        }
        
        return answer;
    }
}
반응형