Leetcode summary: Monostone Stack problem

42. Trapping Rain Water

在这里插入图片描述

class Solution(object):
    def trap(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        st=[]  #use decrease stack here
        ret=0
        i=0
        while i <len(height): #use while here, check again when pop a small one
            if not st or height[i]<=height[st[-1]]:
                st.append(i)
                i+=1
            else:
                index=st.pop()
                if not st: #cannot just only one height,must have a hole
                    continue
                ret+=(min(height[st[-1]],height[i])-height[index])*(i-st[-1]-1)
                
        return ret

11. Container With Most Water

在这里插入图片描述
要找出最大的面积,使用双指针的方法。

#
# @lc app=leetcode id=11 lang=python
#
# [11] Container With Most Water
#
class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        i=0
        j=len(height)-1

        res=0
        while i<j:
            res=max(res,min(height[i],height[j])*(j-i))

            if height[i]<height[j]:
                i=i+1
            else:
                j=j-1

        return res

84. Largest Rectangle in Histogram

在这里插入图片描述

class Solution(object):
    def largestRectangleArea(self, heights):
        """
        :type heights: List[int]
        :rtype: int
        """
        st=[]      # use increase stack 
        h=heights
        h.append(0) #append 0 to the end, caculate whole max at the end of list
        
        i=0
        ret=0
        while i<len(h):
            if not st or h[st[-1]]<=h[i]:
                st.append(i)
                i+=1
            else:
                index=st.pop()
                val=0
                if not st: #only one element, and it is the smallest one until to i
                    val=h[index]*i  #
                else:
                    val=h[index]*(i-st[-1]-1)
                ret=max(ret,val)
                
        return ret
class Solution(object):
    def largestRectangleArea(self, heights):
        """
        :type heights: List[int]
        :rtype: int
        """
        heights.append(0)
        stack = [-1]
        ans = 0
        for i in xrange(len(heights)):
            while heights[i] < heights[stack[-1]]:
                h = heights[stack.pop()]
                w = i - stack[-1] - 1
                ans = max(ans, h * w)
            stack.append(i)
        heights.pop()
        return ans

402. Remove K Digits

Tag: medium
Input: num = “1432219”, k = 3
Output: “1219”
Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.

class Solution(object):
    def removeKdigits(self, num, k):
        """
        :type num: str
        :type k: int
        :rtype: str
        """
        ret=[]
        for c in num:
            #pop out the number when next small than the last
            while k and ret and int(ret[-1])>int(c):
                ret.pop()
                k-=1
            
            if ret or c!='0': #ignore the leading zero
                ret.append(c)
            
        #come here,still need to check the ret,
        while ret and k:
            k-=1
            ret.pop()
            
        if not ret:
            return "0"
        else:
            return "".join(ret)

456. 132 Pattern

Example 1:
Input: [1, 2, 3, 4]

Output: False

Explanation: There is no 132 pattern in the sequence.
Example 2:
Input: [3, 1, 4, 2]

Output: True

Explanation: There is a 132 pattern in the sequence: [1, 4, 2].

class Solution(object):
    def find132pattern(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        th=-sys.maxint
        st=[]  
        for n in nums[::-1]: #important, should tranverse from the end
            if n<th:
                return True
            
            while st and n>st[-1]:
                th=st.pop()    
            
            st.append(n)
            
        return False

注意:这边不能从头开始遍历,应该从尾部开始遍历,依次找到最大值和次大值,
如果从首部开始遍历,采用递减栈,会卡在诸如下面的case:
4,1,3,2
这样永远找不到第一个元素

1019. Next Greater Node In Linked List

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def nextLargerNodes(self, head):
        """
        :type head: ListNode
        :rtype: List[int]
        """
        ret=[]
        st=[]
        index=0
        #using a mono decrease stack to record the number, when find a number bigger than top of stack, then mark the corresponding position with the current value
        cur=head
        while cur:
            ret.append(0)
            while st and cur.val>st[-1][1]:
                ret[st[-1][0]]=cur.val
                st.pop()
                
            st.append((index,cur.val))
            cur=cur.next
            index+=1
        return ret
        

496. Next Greater Element I

You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1’s elements in the corresponding places of nums2.

The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.

Example 1:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
For number 1 in the first array, the next greater number for it in the second array is 3.
For number 2 in the first array, there is no next greater number for it in the second array, so output -1.
Example 2:
Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
For number 2 in the first array, the next greater number for it in the second array is 3.
For number 4 in the first array, there is no next greater number for it in the second array, so output -1.

def nextGreaterElement(self, nums1, nums2):
	dic={}
	st=[]
	for n in nums2:
		while st and st[-1]<n:
			cur=st.pop()
			dic[cur]=n
		st.append(n)
	for n in st:
		dic[n]=-1
	ret=[]
	for n in nums1:
		ret.append(dic[n])
	return ret

503. Next Greater Element II

Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn’t exist, output -1 for this number.

Example 1:
Input: [1,2,1]
Output: [2,-1,2]
Explanation: The first 1’s next greater number is 2;
The number 2 can’t find next greater number;
The second 1’s next greater number needs to search circularly, which is also 2.

#Brute force way
    def nextGreaterElements(self, nums):
   		ret=[-1 for i in range(len(nums))]
    	for i in range(len(nums)):
    		for j in range(i+1,2*len(nums)):
    			if nums[j%len(nums)]>nums[i]:
    				ret[i]=nums[j%len(nums)]
    	return ret
# use mono decrease stack
	def nextGreaterElements(self, nums):
		st=[]
		ret=[-1 for i in range(len(nums))]
		for i in range(2*len(nums)):
			while st and nums[st[-1]%len(nums)]<nums[i]:
				index=st.pop()
				#if ret[index%len(nums)]!=-1:
				ret[index%len(nums)]=nums[i%len(nums)]
			st.append(i)
		return ret
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值