и посмотреть медиа
JavaScript | LeetCode
и посмотреть медиа
LeetCode tasks and solutions in JavaScript. Ideal for interview preparation and improving algorithm skills.
LeetCode tasks and solutions in JavaScript. Ideal for interview preparation and improving algorithm skills.
AI bot for text-to-speech and voice cloning in Telegram. Create audio using neural network quickly and easily.
The channel is dedicated to solving LeetCode tasks in JavaScript. It contains code examples for popular algorithmic problems frequently encountered in interviews. The materials will help master data structures, sorting, dynamic programming, and other key topics. Suitable for junior and middle developers looking to improve their skills.
Задача: 232. Implement Queue using Stacks Сложность: easy Реализуйте очередь (FIFO) с использованием только двух стеков. Реализованная очередь должна поддерживать все функции обычной очереди (push, peek, pop и empty). Реализуйте класс MyQueue: void push(int x) добавляет элемент x в конец очереди. int pop() удаляет элемент из начала очереди и возвращает его. int peek() возвращает элемент из начала очереди. boolean empty() возвращает true, если очередь пуста, и false в противном случае. Пример: Input ["MyQueue", "push", "push", "peek", "pop", "empty"] [[], [1], [2], [], [], []] Output [null, null, null, 1, 1, false] Explanation MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: [1] myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is [2] myQueue.empty(); // return false 👨💻 Алгоритм: 1⃣Добавление элемента: Для метода push(int x) переместите все элементы из стека s1 в стек s2. Добавьте элемент x в стек s2. Затем переместите все элементы обратно из стека s2 в стек s1. Если стек s1 пуст, обновите переменную front значением x. 2⃣Удаление и проверка первого элемента: Для метода pop() удалите элемент из начала очереди, извлекая верхний элемент из стека s1. Обновите переменную front на новый верхний элемент стека s1, если он не пуст. Для метода peek() верните значение переменной front, так как она всегда хранит первый элемент очереди. 3⃣Проверка на пустоту: Для метода empty() верните результат проверки, является ли стек s1 пустым. 😎 Решение: class MyQueue { constructor() { this.s1 = []; this.s2 = []; this.front = null; } push(x) { if (this.s1.length === 0) { this.front = x; } while (this.s1.length > 0) { this.s2.push(this.s1.pop()); } this.s2.push(x); while (this.s2.length > 0) { this.s1.push(this.s2.pop()); } } pop() { const res = this.s1.pop(); if (this.s1.length > 0) { this.front = this.s1[this.s1.length - 1]; } return res; } empty() { return this.s1.length === 0; } peek() { return this.front; } } Ставь 👍 и забирай 📚 Базу знаний
Открыть канал и посмотреть медиаOnly registered users can share their opinion.
Be the first to share your impression of this resource!