и посмотреть медиа
JavaScript LeetCode
и посмотреть медиа
Tareas y soluciones de LeetCode en JavaScript. Ideal para la preparación de entrevistas y la mejora de habilidades de algoritmo.
Tareas y soluciones de LeetCode en JavaScript. Ideal para la preparación de entrevistas y la mejora de habilidades de algoritmo.
bot de IA para clonar texto a voz y voz en Telegram. Cree audio utilizando la red neuronal de forma rápida y fácil.
El canal está dedicado a resolver las tareas de LeetCode en JavaScript. Contiene ejemplos de códigos para problemas algoritmos populares que se encuentran frecuentemente en entrevistas. Los materiales ayudarán a dominar estructuras de datos, clasificación, programación dinámica y otros temas clave.
Задача: 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; } } Ставь 👍 и забирай 📚 Базу знаний
Открыть канал и посмотреть медиаSolo los usuarios registrados pueden compartir su opinión.
¡Sé el primero en compartir tu experiencia con este recurso!