2022이전/알고리즘(하루에하나씩!)
다리를 지나는 트럭(Queue 개념)
바로퇴장
2020. 2. 28. 18:29
문제 : https://programmers.co.kr/learn/courses/30/lessons/42583
코딩테스트 연습 - 다리를 지나는 트럭 | 프로그래머스
트럭 여러 대가 강을 가로지르는 일 차선 다리를 정해진 순으로 건너려 합니다. 모든 트럭이 다리를 건너려면 최소 몇 초가 걸리는지 알아내야 합니다. 트럭은 1초에 1만큼 움직이며, 다리 길이는 bridge_length이고 다리는 무게 weight까지 견딥니다. ※ 트럭이 다리에 완전히 오르지 않은 경우, 이 트럭의 무게는 고려하지 않습니다. 예를 들어, 길이가 2이고 10kg 무게를 견디는 다리가 있습니다. 무게가 [7, 4, 5, 6]kg인 트럭이 순서
programmers.co.kr
import java.util.*;
class Solution {
public int solution(int bridge_length, int weight, int[] truck_weights) {
int answer = 0;
int time = 0;
int bridge_weight = 0;
int i = 0;
Queue<Integer> bridge = new LinkedList<Integer>();
Queue<Integer> arrive_time = new LinkedList<Integer>();
while(i < truck_weights.length){
if(bridge_weight + truck_weights[i] <= weight){
bridge.add(truck_weights[i]);
bridge_weight = bridge_weight + truck_weights[i];
arrive_time.add(++time);
if(i == truck_weights.length-1){
time = time + bridge_length;
}
i++;
}
else{
time++;
}
if(arrive_time.peek()+bridge_length == time+1){
bridge_weight = bridge_weight - bridge.poll();
arrive_time.poll();
}
}
answer = time;
return answer;
}
}
주로 사용했던 메소드
Queue
- - 자료구조 중 하나
- - 선입선출
- - FIFO( First In First Out )
- Queue<Integer> bridge = new LinkedList<Integer>() : Integer 형태의 queue를 만들어준다.
- Queue.add("$$") : Queue에 삽입
- Queue.poll("$$") : Queue에 빼내기
- Queue.peek() : Queue 최상단 보여주기
- Queue.size() : Queue 크기
- Queue.isEmpty() : Queue가 비어있는가?(boolean)
- Queue.contain("$$") : Queue에 해당 요소가 존재하는가(boolean)
더 좋은 방법은 머가 있을까?