기존 풀이
import java.util.*;
class Solution {
public int solution(int bridge_length, int weight, int[] truck_weights) {
int answer = 1;
int tot_weight = 0;
Queue<Truck> q = new LinkedList<Truck>();
Queue<Truck> q2 = new LinkedList<Truck>();
for (int i = 0 ; i < truck_weights.length ; i++) {
q.offer(new Truck(bridge_length, truck_weights[i]));
}
tot_weight += q.peek().weight;
q2.offer(q.poll());
while (!q2.isEmpty()) {
for(Truck truck : q2) {
truck.time--;
}
if(q2.peek().time == 0) {
tot_weight -= q2.poll().weight;
}
if(!q.isEmpty() && tot_weight + q.peek().weight <= weight) {
tot_weight += q.peek().weight;
q2.offer(q.poll());
}
answer++;
}
return answer;
}
}
class Truck {
int time;
int weight;
public Truck(int time, int weight) {
this.time = time;
this.weight = weight;
}
}
다른 사람의 풀이
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 풀이 (0) | 2020.04.17 |
---|---|
프로그래머스 라면공장 Java 풀이 (0) | 2020.04.17 |
프로그래머스 N으로 표현 Java 풀이 (0) | 2020.04.15 |
프로그래머스 타겟 넘버 Java 풀이 (0) | 2020.04.15 |
프로그래머스 탑 Java 풀이 (0) | 2020.04.09 |