반응형
https://school.programmers.co.kr/learn/courses/30/lessons/42586
풀이
세상에 중간 단계의 알고리즘은 없는 걸까? 체감상 순한맛, 매운맛밖에 없는 것 같다..
이번 알고리즘 문제는 배열로만 해결할 수도 있고, 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;
}
}
반응형
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[프로그래머스]JAVA - Level1. 같은 숫자는 싫어 (0) | 2022.09.01 |
---|---|
[프로그래머스]JAVA - Level2. 가장 큰 수 (0) | 2022.09.01 |
[프로그래머스]JAVA - Level3. 코딩 테스트 공부 (2) | 2022.08.29 |
[프로그래머스]JAVA - Level1. 성격 유형 검사하기 (0) | 2022.08.27 |
[프로그래머스]JAVA - Level1. 신규 아이디 추천 (0) | 2022.08.23 |