Lesson 4 (Counting Elements) - PermCheck(Easy)
Test results - Codility
A non-empty array A consisting of N integers is given. A permutation is a sequence containing each element from 1 to N once, and only once. For example, array A such that: A[0] = 4 A[1] = 1 A[2] = 3 A[3] = 2 is a permutation, but array A such that: A[0] =
app.codility.com
배열의 값들이 연속적인 값이면 1을, 그렇지 않다면 0을 출력하는 문제입니다.
시도1 (실패)
function solution(A) {
return A.every(num => num <= A.length) ? 1 : 0;
}
[2, 2, 2, 2] 면 통과하지 못하는 코드.
스트레스 테스트를 하지 않더라도 반복값 테스트와 경계값 테스트는 꼭 하는 습관을 들입시다.
지금 새벽이라 컨디션이 좋지않군요.
시도2 (성공)
function solution(A) {
const table = new Map();
for (let i = 0; i < A.length; i++) {
if (A[i] > A.length) {
return 0;
}
if (!table.get(A[i])) {
table.set(A[i], 1);
} else {
return 0;
}
}
return 1;
}
첫번째 알고리즘에서 중복이 있는지 검사하는 로직도 추가했습니다.
Map 대신 List를 써서 contains로 검사를 해도 되긴한데 조금이라도 시간 복잡도를 줄이기 위해 선택한 방법입니다. 이건 코딜리티니까...
'IT > JavaScript & TypeScript' 카테고리의 다른 글
| [JavaScript/알고리즘] 체육복 (Greedy) (0) | 2025.01.11 |
|---|---|
| [JavaScript/알고리즘] 게임 맵 최단거리 (BFS) (0) | 2025.01.10 |
| [JavaScript/알고리즘] PassingCars (누적값 문제) (0) | 2025.01.08 |
| [JavaScript/알고리즘] FrogRiverOne (0) | 2025.01.07 |
| [JavaScript/알고리즘] TapeEquilibrium (feat. 경계값 테스트) (0) | 2025.01.05 |