프로그래머스/Lv.2
코딩테스트 연습 > 다리를 지나는 트럭 - JAVA (Queue)
아찌방
2024. 2. 4. 12:46
https://school.programmers.co.kr/learn/courses/30/lessons/42583
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이 - 나의 생각
큐를 트럭과 다리를 담당하도록
2개를 선언했다.
1. Truck Queue
우선 Queue에 truck을 다 집어 넣는다.
2. Bridge Queue
우선 Queue에 다리 길이 만큼 0을 다 집어 넣는다.
이때 0은 truck이 올라가 있지 않다는 것을 의미한다.
3. 반복문 돌리기
while문으로 Bridge Queue가 비어 있지 않는 경우 반복문을 돌린다.
다리에 올라가 있는 트럭의 무게를 체크하면서
다음 트럭을 올려도 되는지, 안 되는지 파악한다.
코드
import java.util.*;
class Solution {
public int solution(int bridge_length, int weight, int[] truck_weights) {
int time = 0;
int current_weight = 0;
Queue<Integer> bridge = new LinkedList<>();
Queue<Integer> trucks = new LinkedList<>();
for(int truck : truck_weights){
trucks.offer(truck);
}
for(int i = 0; i < bridge_length; i++){
bridge.offer(0);
}
while(!bridge.isEmpty()){
int passed_truck = bridge.poll();
current_weight -= passed_truck;
if(!trucks.isEmpty()){
int next_truck = trucks.peek();
if(current_weight + next_truck <= weight){
bridge.offer(trucks.poll());
current_weight += next_truck;
}else{
bridge.offer(0);
}
}
time++;
}
return time;
}
}
728x90