๐ข Algorithm
[Javascript][Programmers] ์นด๋ ๋ญ์น
์ค๋๊ธฐ
2024. 8. 16. 11:39
๋ฐ์ํ
๋ฌธ์
๋ฌธ์ ์๋ ๋ค์๊ณผ ๊ฐ์ ์กฐ๊ฑด์ด ์ ์๋์ด ์์ต๋๋ค.
- ์นด๋ ๋ญ์น์์ ์นด๋๋ฅผ ์์๋๋ก ์ฌ์ฉํฉ๋๋ค.
- ์นด๋๋ฅผ ์ฌ์ฉํ์ง ์๊ณ ๋ค์ ์นด๋๋ก ๋์ด๊ฐ ์ ์์ต๋๋ค.
- ๊ธฐ์กด์ ์ฃผ์ด์ง ์นด๋ ๋ญ์น์ ๋จ์ด ์์๋ ๋ฐ๊ฟ ์ ์์ต๋๋ค.
์ด๋ฌํ ์กฐ๊ฑด๋ค์ ๊ณ ๋ คํด๋ณด๋ฉด, ์ด ๋ฌธ์ ๋ "์ ์ ์ ์ถ(FIFO: First In, First Out)" ์์น์ ๋ฐ๋ฅด๊ณ ์์์ ์ ์ ์์ต๋๋ค. ์ด๋ฐ ํน์ฑ์ ๊ฐ์ฅ ์ ๊ตฌํํ ์ ์๋ ์๋ฃ๊ตฌ์กฐ๋ ํ(Queue)์ ๋๋ค.
๋์ ํ์ด
- ์๊ฐ๋ณต์ก๋: O(M) (cards์ ๊ธธ์ด: N, goal์ ๊ธธ์ด: M)
function solution(cards1, cards2, goal) {
let index1 = 0;
let index2 = 0;
for (let goalIndex = 0; goalIndex < goal.length; goalIndex++) {
if (index1 < cards1.length && goal[goalIndex] === cards1[index1]) {
index1++;
} else if (index2 < cards2.length && goal[goalIndex] === cards2[index2]) {
index2++;
} else {
return "No";
}
}
return "Yes";
}
๋ค๋ฅธ ํ์ด
์ง์ ํ๋ฅผ ๊ตฌํํ์ฌ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ ์๋ ์์ต๋๋ค.
- ์๊ฐ๋ณต์ก๋: O(M)
class Queue {
items = [];
front = 0;
rear = 0;
// ์์ฑ์๋ฅผ ์ด์ฉํด ํธํ๊ฒ ์ด๊ธฐํ
constructor(array) {
this.items = array;
this.rear = array.length;
}
push(item) {
this.items.push(item);
this.rear++;
}
pop() {
return this.items[this.front++];
}
first() {
return this.items[this.front];
}
isEmpty() {
return this.front === this.rear;
}
}
function solution(cards1, cards2, goal) {
// cards์ goal์ Queue๋ก ๋ณํ
cards1 = new Queue(cards1);
cards2 = new Queue(cards2);
goal = new Queue(goal);
// โ goal์ ๋ฌธ์์ด์ ์์ฐจ์ ์ผ๋ก ์ํ
while (!goal.isEmpty()) {
if (!cards1.isEmpty() && cards1.first() === goal.first()) { // โ card1์ front์ ์ผ์นํ๋ ๊ฒฝ์ฐ
cards1.pop();
goal.pop();
} else if (!cards2.isEmpty() && cards2.first() === goal.first()) { // โ card2์ front์ ์ผ์นํ๋ ๊ฒฝ์ฐ
cards2.pop();
goal.pop();
} else {
break;
}
}
return goal.isEmpty() ? "Yes" : "No"; // โ goal์ด ๋น์์ผ๋ฉด “Yes” ์๋๋ฉด “No”๋ฅผ ๋ฐํ
}
Reference
๋ฐ์ํ