LeetCode 面试题 03.05. 栈排序

一、题目

  栈排序。 编写程序,对栈进行排序使最小元素位于栈顶。最多只能使用一个其他的临时栈存放数据,但不得将元素复制到别的数据结构(如数组)中。该栈支持如下操作:pushpoppeekisEmpty。当栈为空时,peek 返回 -1

  点击此处跳转题目

示例1:

输入:
[“SortedStack”, “push”, “push”, “peek”, “pop”, “peek”]
[[], [1], [2], [], [], []]
输出:
[null,null,null,1,null,2]

示例2:

输入:
[“SortedStack”, “pop”, “pop”, “push”, “pop”, “isEmpty”]
[[], [], [], [1], [], []]
输出:
[null,null,null,null,null,true]

说明:

  • 栈中的元素数目在[0, 5000]范围内。

二、C# 题解

  很基础的题目,直接上代码:

public class SortedStack {
    
    
    private int[] st;
    private int p;

    public SortedStack() {
    
    
        st = new int[5001];
        p = -1;
    }
    
    public void Push(int val) {
    
    
        if (p == st.Length - 1) return;

        int i;
        for (i = p; i >= 0 && st[i] < val; i--) {
    
    
            st[i + 1] = st[i];
        }
        st[i + 1] = val;
        p++;
    }
    
    public void Pop() {
    
    
        if (p == -1) return;
        p--;
    }
    
    public int Peek() {
    
    
        if (p == -1) return -1;
        return st[p];
    }
    
    public bool IsEmpty() {
    
    
        return p == -1;
    }
}

/**
 * Your SortedStack object will be instantiated and called as such:
 * SortedStack obj = new SortedStack();
 * obj.Push(val);
 * obj.Pop();
 * int param_3 = obj.Peek();
 * bool param_4 = obj.IsEmpty();
 */
  • 时间复杂度:无。
  • 空间复杂度:无。

猜你喜欢

转载自blog.csdn.net/zheliku/article/details/132741583
今日推荐