155. Min Stack

LeetCode medium оригинал: C# #array #csharp #design #leetcode #math #medium #stack

Разработайте стек, который поддерживает операции добавления элемента, удаления элемента, получения верхнего элемента и извлечения минимального элемента за постоянное время.

Реализуйте класс MinStack:

MinStack() инициализирует объект стека.

void push(int val) добавляет элемент val в стек.

void pop() удаляет элемент на вершине стека.

int top() возвращает верхний элемент стека.

int getMin() извлекает минимальный элемент в стеке.

C# решение

сопоставлено/оригинал
public class MinStack {
    private Stack<int[]> stack = new Stack<int[]>();
    public MinStack() {
    }
    public void Push(int x) {
        if (stack.Count == 0) {
            stack.Push(new int[] { x, x });
            return;
        }
        int current_min = stack.Peek()[1];
        stack.Push(new int[] { x, Math.Min(x, current_min) });
    }
    public void Pop() {
        stack.Pop();
    }
    public int Top() {
        return stack.Peek()[0];
    }
    public int GetMin() {
        return stack.Peek()[1];
    }
}

C++ решение

auto-draft, проверить перед отправкой
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
public class MinStack {
    private stack<int[]> stack = new stack<int[]>();
    public MinStack() {
    }
    public void Push(int x) {
        if (stack.size() == 0) {
            stack.push(new int[] { x, x });
            return;
        }
        int current_min = stack.Peek()[1];
        stack.push(new int[] { x, min(x, current_min) });
    }
    public void Pop() {
        stack.pop();
    }
    public int Top() {
        return stack.Peek()[0];
    }
    public int GetMin() {
        return stack.Peek()[1];
    }
}

Java решение

сопоставлено/оригинал
class MinStack {
    private Stack<int[]> stack = new Stack<>();

    public MinStack() {}

    public void push(int x) {
        if (stack.isEmpty()) {
            stack.push(new int[] { x, x });
            return;
        }

        int currentMin = stack.peek()[1];
        stack.push(new int[] { x, Math.min(x, currentMin) });
    }

    public void pop() {
        stack.pop();
    }

    public int top() {
        return stack.peek()[0];
    }

    public int getMin() {
        return stack.peek()[1];
    }
}

JavaScript решение

сопоставлено/оригинал
function last(arr) {
    return arr[arr.length - 1];
}

class MinStack {
    _stack = [];

    push(x) {
        if (this._stack.length === 0) {
            this._stack.push([x, x]);
            return;
        }

        const currentMin = last(this._stack)[1];
        this._stack.push([x, Math.min(currentMin, x)]);
    }

    pop() {
        this._stack.pop();
    }

    top() {
        return last(this._stack)[0];
    }

    getMin() {
        return last(this._stack)[1];
    }
}

Python решение

сопоставлено/оригинал
class MinStack:

    def __init__(self):
        self.stack = []

    def push(self, x: int) -> None:
        if not self.stack:
            self.stack.append((x, x))
            return
        current_min = self.stack[-1][1]
        self.stack.append((x, min(x, current_min)))

    def pop(self) -> None:
        self.stack.pop()

    def top(self) -> int:
        return self.stack[-1][0]

    def getMin(self) -> int:
        return self.stack[-1][1]

Go решение

сопоставлено/оригинал
type MinStack struct {
    stack [][]int
}

func Constructor() MinStack {
    return MinStack{stack: make([][]int, 0)}
}

func (this *MinStack) Push(val int) {
    if len(this.stack) == 0 {
        this.stack = append(this.stack, []int{val, val})
        return
    }

    currentMin := this.stack[len(this.stack)-1][1]
    this.stack = append(this.stack, []int{val, min(val, currentMin)})
}

func (this *MinStack) Pop() {
    this.stack = this.stack[:len(this.stack)-1]
}

func (this *MinStack) Top() int {
    return this.stack[len(this.stack)-1][0]
}

func (this *MinStack) GetMin() int {
    return this.stack[len(this.stack)-1][1]
}

func min(x, y int) int {
    if x < y {
        return x
    }
    return y
}

Вакансии для этой задачи

Показаны активные вакансии с пересечением по тегам задачи.

Все вакансии
Активных вакансий пока нет.