1. 문제
https://programmers.co.kr/learn/courses/30/lessons/42583?language=java
코딩테스트 연습 - 다리를 지나는 트럭
트럭 여러 대가 강을 가로지르는 일 차선 다리를 정해진 순으로 건너려 합니다. 모든 트럭이 다리를 건너려면 최소 몇 초가 걸리는지 알아내야 합니다. 트럭은 1초에 1만큼 움직이며, 다리 길이
programmers.co.kr
2. 나의 풀이
import java.util.*;
class Solution {
public int solution(int bridge_length, int weight, int[] truck_weights) {
int answer = 0;
Queue <Integer> q = new LinkedList <Integer>();
int mugae = 0;
for(int i : truck_weights) {
while(true) {
if(q.isEmpty()) {
q.offer(i);
mugae += i;
answer++;
break;
}else if(q.size() == bridge_length) {
mugae -= q.poll();
}else {
if(mugae + i > weight) {
q.offer(0);
answer++;
}else {
q.offer(i);
mugae += i;
answer++;
break;
}
}
}
}
return answer + bridge_length;
}
}
3. 다른 사람 풀이
import java.util.*;
class Solution {
class Truck {
int weight;
int move;
public Truck(int weight) {
this.weight = weight;
this.move = 1;
}
public void moving() {
move++;
}
}
public int solution(int bridgeLength, int weight, int[] truckWeights) {
Queue<Truck> waitQ = new LinkedList<>();
Queue<Truck> moveQ = new LinkedList<>();
for (int t : truckWeights) {
waitQ.offer(new Truck(t));
}
int answer = 0;
int curWeight = 0;
while (!waitQ.isEmpty() || !moveQ.isEmpty()) {
answer++;
if (moveQ.isEmpty()) {
Truck t = waitQ.poll();
curWeight += t.weight;
moveQ.offer(t);
continue;
}
for (Truck t : moveQ) {
t.moving();
}
if (moveQ.peek().move > bridgeLength) {
Truck t = moveQ.poll();
curWeight -= t.weight;
}
if (!waitQ.isEmpty() && curWeight + waitQ.peek().weight <= weight) {
Truck t = waitQ.poll();
curWeight += t.weight;
moveQ.offer(t);
}
}
return answer;
}
}
'알고리즘 공부 > 프로그래머스' 카테고리의 다른 글
(Java)프로그래머스 코딩테스트 연습 - 2020 KAKAO BLIND RECRUITMENT - 문자열 압축 (0) | 2020.11.13 |
---|---|
(Java)프로그래머스 코딩테스트 연습 - 스택/큐 - 프린터 (0) | 2020.11.13 |
(Java)프로그래머스 코딩테스트 연습 - 2019 KAKAO BLIND RECRUITMENT - 실패율 (0) | 2020.11.10 |
(Java)프로그래머스 코딩테스트 연습 - 연습문제 - 하샤드 수 (0) | 2020.11.10 |
(Java)프로그래머스 코딩테스트 연습 - 월간 코드 챌린지 시즌1 - 3진법 뒤집기 (0) | 2020.11.10 |