11. 다리를 지나는 트럭 JAVA (프로그래머스)
by BFine반응형
가. 문제파악
1. 유형 : 큐
- 생각보다 어렵게 느껴졌던 문제.. 구현하면서 생각하다보니 조금 지저분해졌다..
- 때로는 단순한 방법으로도 해결할 수 있다는 것을 생각하자!
나. 코드
1. 풀이 : 다리에 있는 시간을 큐로 만들자!
- 조건
1. 다리는 큐이고 다리의 길이가 끝나는 지점이 큐에서 Poll을 해주는 것이다.
2. 다리에서 빠져나갔으니 중량에서 그만큼을 빼준다.
3. 중량이 가능하면 큐에 트럭을 추가하고 안되면 -1를 추가하자(1초에 의미)
- 트럭이 한대면 대응을 못해서 하나의 경우에 대해 예외처리를 해줬다 ...
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
public static void main(String[] args) {
System.out.println(new Solution().solution(100,100,new int[]{10}));
}
public int solution(int bridge_length, int weight, int[] truck_weights) {
int time = 1;
int idx = 1;
int last = truck_weights.length-1;
Queue<Integer> wait = new LinkedList<>();
int total = truck_weights[0];
wait.add(0);
if(truck_weights.length == 1){
return bridge_length+1;
}
while(!wait.isEmpty()){
time++;
if(wait.peek() == last ) break;
if(wait.size() == bridge_length){
int id= wait.poll();
if(id != -1){
total -= truck_weights[id];
}
}
if(idx <= last && total + truck_weights[idx] <= weight){
total+= truck_weights[idx];
wait.add(idx++);
}else{
wait.add(-1);
}
}
return time;
}
}
반응형
블로그의 정보
57개월 BackEnd
BFine