프로그래머스 - 다리를 지나는 트럭 (Level 2)

2024. 2. 22. 22:10코딩테스트 정리(자바)

728x90

큐를 0으로 채워서 다리를 만드는 방법이 있었다.

이걸 생각해내지 못해 실패했다.

 

import java.util.*;

public class Solution {
    public int solution(int bridgeLength, int weight, int[] truckWeights) {
        int bridgeWeight = 0;
        Queue<Integer> bridge = new LinkedList<>();

        for (int i = 0; i < bridgeLength; i++) { //다리 만들기
            bridge.add(0);
        }

        int time = 0;
        int truckIndex = 0;
        while (truckIndex < truckWeights.length) { //트럭 마지막 인덱스까지
            bridgeWeight -= bridge.poll(); //다리 무게에서 큐의 맨앞에 담겨진 트럭 무게 빼기 -> 건널 수 있는 남은 무게

            int truckWeight = truckWeights[truckIndex];
            if (bridgeWeight + truckWeight <= weight) { //더 건널 수 있는 무게인지 확인 후 담기
                bridge.add(truckWeight);
                bridgeWeight += truckWeight;
                truckIndex++;
            } else { //아니라면 0을 담기
                bridge.add(0);
            }

            time++;
        }

        while (bridgeWeight > 0) { //다리에 남아있는 트럭이 있다면(마지막 남겨진 트럭) time++
            bridgeWeight -= bridge.poll();
            time++;
        }

        return time;
    }
}

 

 


나만의 코드로 풀이

 

import java.util.*;

class Solution {
    public int solution(int bridge_length, int weight, int[] truck_weights) {
        Queue <Integer> q=new LinkedList<>();
        int time=0;
        int index=0;
        int current_weight=weight;
        int truck=0;
        int len=truck_weights.length;
        for(int i=0;i<bridge_length;i++){ //다리 만들기
            q.add(0);
        }
        
        while(index!=len){
            current_weight+=q.poll();
            truck=truck_weights[index];
            
            if(current_weight>=truck){
                q.add(truck);
                
                current_weight-=truck;
                 index++;
            }
            else{
                q.add(0);
                
            }
            time++;
        }
        
        
        
        return time+bridge_length; //남아있는 트럭 때문에 다리길이만큼의 시간 추가
    }
}
728x90