Solution based on simple array and resizing


  • 0
    A
      public class MinStack
            {
    
                /** initialize your data structure here. */
                private int[] arr;
                private int index;
                private int currentSize;
                public MinStack()
                {
                    this.currentSize = 10;
                    this.arr = new int[this.currentSize];
                    this.index = 0;
                }
    
                private void Resize()
                {
                    this.currentSize *= 2;
                    int[] copyArr = new int[this.currentSize];
                    for (int i = 0; i < this.index; i++)
                    {
                        copyArr[i] = this.arr[i];
                    }
                    this.arr = copyArr;
                }
    
                public void Push(int x)
                {
                    this.arr[this.index++] = x;
                    if (this.index == this.currentSize)
                    {
                        this.Resize();
                    }
                }
    
                public void Pop()
                {
                    this.index--;
                }
    
                public int Top()
                {
                    if(index ==0)
                    {
                        return 0;
                    }
                    return this.arr[index-1];
                }
    
                public int GetMin()
                {
                    int min = this.arr[0];
                    for (int i = 0; i < this.index; i++)
                    {
                        if (this.arr[i] < min)
                        {
                            min = this.arr[i];
                        }
                    }
                    return min;
                }
            }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.