코딩테스트 공부
[LeetCode] 1701. Average Waiting Time - 자바스크립트 0617
codevil
2022. 6. 17. 13:02
https://leetcode.com/problems/average-waiting-time/
Average Waiting Time - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
음식점에서 평균적으로 얼마나 손님들이 시간을 소요하는지 문제를 구하는 문제이다. 문제에는, 손님들이 온 시간과 먹은 시간이 기록된 리스트가 주어져 있다.
문제풀이
1. 현재 시간을 선언한다. 이때 손님이 온 시간을 모르니 0으로 선언한다.
2. 전체 시간을 선언한다. 시간이 소요될 때마다 시간을 더한다. 처음 선언할 때는 0으로 선언한다.
let currentTime = 0;
let wholeTime = 0
3. 주어진 arr에 for loop문을 적용한다. 이때 customer[i][0]을 waitingTIme, customer[i][1]을 eatingTime으로 한다.
for (let i = 0; i < customers.length; i++) {
const [waitingTime, eatingTime] = customers[i]
}
4. 손님이 입장한 시간부터 시간을 세야하기 때문에 만일 currentTime이 waitingTIme보다 작다면 둘이 같게 만들어준다.
for (let i = 0; i < customers.length; i++) {
const [waitingTime, eatingTime] = customers[i]
if (currentTime < waitingTime) {
currentTime = waitingTime
}
}
5. 전체시간에, 현재시간-waitingTime + eatingTime을 더해준다. 현재 손님이 도착한시간과 이전 손님이 먹고 있는 시간의 차이와 현재 손님이 먹는 시간을 더한 값이다.
6. 현재시간을 먹는 시간에 더해준다.
for (let i = 0; i < customers.length; i++) {
const [waitingTime, eatingTime] = customers[i]
if (currentTime < waitingTime) {
currentTime = waitingTime
}
wholeTime += currentTime - waitingTime + eatingTime
currentTime += eatingTime
}
최종 풀이
var averageWaitingTime = function (customers) {
let currentTime = 0;
let wholeTime = 0
for (let i = 0; i < customers.length; i++) {
const [waitingTime, eatingTime] = customers[i]
if (currentTime < waitingTime) {
currentTime = waitingTime
}
wholeTime += currentTime - waitingTime + eatingTime
currentTime += eatingTime
}
return wholeTime / customers.length
};