반응형
Q. Cyclic Rotation
function solution(A, K) {
let result = new Array(A.length);
for (let i = 0; i < result.length; i++) {
result[(i + K) % A.length] = A[i]
}
return result;
}
console.log(solution(A:[1, 2, 3, 4, 5], K:2)); // [3, 4, 5, 1, 2]
Q. Frog River One // return time when frog can cross
function solution(X, A) {
let river_positions = new Array(arrayLength:X + 1).fill(value:false);
for (let time = 0; time < A.length; time++) {
let pos = A[time];
if (!river_positions[pos]) {
river_positions[pos] = true;
X -= 1;
if (X === 0) return time;
}
}
return -1;
}
console.log(solution(X:3, A:[1, 2, 1]));
Q. Max Counter
function solution(N, A) {
let counters = new Array(N).fill(0);
let start_line = 0;
let current_max = 0;
A.forEach(instruction => {
let index = instruction - 1
if (instruction > N) start_line = current_max;
else if (counters[index] < start_line) counters[index] = start_line + 1;
else counters[index] += 1;
if (instruction <= N && counters[index] > current_max) current_max = counters[index];
});
for (let i = 0; i < counters.length; i++) {
if (counters[i] < start_line) counters[i] = start_line;
}
return counters;
}
console.log(solution(5, [3, 4, 4, 6, 1, 4, 4])); // [ 3, 2, 2, 4, 2 ]
반응형