C# accepted answer but is this cheating?


  • -1
    B

    Since getMin() needs to be O(1), I made Pop and Push do the work. Is this cheating? Also, is using a List acceptable here? (This is my first Leetcode submission btw).

        public class MinStack
        {
            List<int> item;                         
            int min;
    
            public MinStack()
            {
                item = new List<int>();
            }
    
            public bool IsEmpty()                     
            {
                return item.Count > 0 ? false : true;
            }
    
            public void Push(int x)
            {
                if (this.IsEmpty() || x < min)
                {
                    min = x;
                }
                item.Add(x);
            }
    
            public void Pop()
            {
                var topItemToPop = item[item.Count - 1];
                item.RemoveAt(item.Count - 1);
                // Find new min if top was the min and stack is not empty now
                if (min == topItemToPop && item.Count != 0)
                {
                    min = item[0];
                    foreach (var i in item)
                    {
                        if (i < min)
                        {
                            min = i;
                        }
                    }
                }
            }
    
            public int Top()
            {
                return item[item.Count - 1];
            }
    
            public int GetMin()
            {
                return min;
            }
        }

Log in to reply
 

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