Lesson 3 (Time Complexity) - FrogJmp(Easy)
Test results - Codility
A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D. Count the minimal number of jumps that the smal
app.codility.com
X의 위치에 있는 개구리가 Y와 같거나 먼 위치로 이동하려고 하는데 한번에 D만큼만 이동할 수 있습니다. 이때 최소 몇 번을 이동해야 하는지 구하는 문제입니다.
시간초과가 일어나지 않도록 유의하며 풀어야 합니다.
function solution(X, Y, D) {
let cnt = 0;
while (X < Y) {
X += D;
cnt++;
}
return cnt;
}
쉬운문제넹 하고 이렇게 풀면 바로 시간초과입니다.
function solution(X, Y, D) {
return Math.ceil((Y - X) / D);
}
생각해보니까 반복문을 굳이 쓸 필요가 없는 문제라 위와 같이 수정하니 해결되었습니다.
'IT > JavaScript & TypeScript' 카테고리의 다른 글
[JavaScript/알고리즘] TapeEquilibrium (feat. 경계값 테스트) (0) | 2025.01.05 |
---|---|
[JavaScript/알고리즘] PermMissingElem (0) | 2025.01.05 |
[JavaScript/알고리즘] OddOccurrencesInArray (feat. Map) (0) | 2025.01.04 |
[JavaScript/알고리즘] CyclicRotation (feat. 테스트 케이스) (2) | 2025.01.04 |
[JavaScript/알고리즘] BinaryGap (1) | 2025.01.03 |