TIL Java
내일배움캠프 56일차 TIL _ 12주 3일차
mad038
2024. 7. 8. 15:20
- 오늘 있었던 일
- 스프링 공부
- 알고리즘
알고리즘 문제 풀기
● 다리를 지나는 트럭
더보기
● 다리를 지나는 트럭 //링크
import java.util.LinkedList;
import java.util.Queue;
class Solution {
public int solution(int bridge_length, int weight, int[] truck_weights) {
Queue<int[]> bridge = new LinkedList<>();
Queue<Integer> trucks = new LinkedList<>();
for (int target : truck_weights) {
trucks.add(target);
}
int cur_weight = 0;
int time = 0;
while (!trucks.isEmpty() || !bridge.isEmpty()) {
time++;
if (!bridge.isEmpty() && bridge.peek()[0] <= time) {
int[] exitingTruck = bridge.poll();
cur_weight -= exitingTruck[1];
}
if (!trucks.isEmpty() && cur_weight + trucks.peek() <= weight && bridge.size() < bridge_length) {
int truck = trucks.poll();
cur_weight += truck;
bridge.add(new int[]{time + bridge_length, truck});
}
}
return time;
}
}
-
- 2번만에 통과했다.
- 문제 지문에
- 건너려면 최소 몇 초가 걸리는지 return 하도록 solution 함수를 완성하세요.
- 처음할땐 그냥 넘어갈때 시간을 더하는 식으로 구했지만 통과하지 못했다.
한번에 여러대가 가는것을 생각하지 못했다 - 아에 들어오고 나가는걸 각각 식으로 구해서 통과했다
- 밑은 다른 사람의 풀이
-
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; } }
- 엄청 깔끔하네
당일 회고
- 컴퓨터 하드가 맛이가서 작성해둔 TIL을 못올렸다.
복구데이터가 이제야 올 줄은 몰랐다.