根据题意查找的是数组中左侧和右侧距离最近的比当前值小的数,可采用单调栈的方式求解,右侧最近正序遍历,左侧最近用总长度减去数据倒叙右侧最近 单调栈算法思路:

  1. 正向遍历数组
  2. 判断栈底的值和当前值得关系,如果取较大数,则保证栈顶元素小于当前值,如果取较小值,则保证栈顶元素大于当前值
  3. 将当前元素索引加入到栈中 代码如下
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param nums int一维数组 
# @return int二维数组
#
class Solution:
    def foundStack(self, nums):
        stack = []
        res = [-1 for _ in range(len(nums))]
        for i, num in enumerate(nums):
            if not stack or nums[stack[-1]] < num:
                stack.append(i)
            else:
                while stack and nums[stack[-1]] > num:
                    j = stack.pop()
                    res[j] = i
                stack.append(i)
        return res
                    
                
    def foundMonotoneStack(self , nums ):
        # write code here
        res = []
        s = self.foundStack(nums)
        s_2 = self.foundStack(nums[::-1])[::-1]
        for i in range(len(s)):
            t = [0, 0]
            if s_2[i] == -1:
                t[0] = s_2[i]
            else:
                t[0] = len(nums) - s_2[i] - 1
            t[1] = s[i]
            res.append(t)
        return res