使用单调栈递增性质,确定左右两侧的最近较小值位置;

以下为Swift解法:

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param nums int整型一维数组
     * @return int整型二维数组
     */
    func foundMonotoneStack(_ nums: [Int]) -> [[Int]] {
        let count = nums.count
        var res: [[Int]] = [[Int]](repeating: [Int](repeating: -1, count: 2), count: count)

        // 示例:[3, 4, 1, 5, 6, 2, 7]
        // 栈中存放的是每个元素的位置
        var stack: [Int] = []
        // 使用栈,正序保持单调递增,确定i左侧最近较小值位置
        for i in 0 ..< count {
            while !stack.isEmpty && nums[stack.last!] >= nums[i] {
                // 如果栈里记录的位置的值比i位置的值大,就持续pop,直到找到一个最近较小位置
                stack.removeLast()
            }

            if stack.isEmpty {
                // 栈已为空,i位置左侧没有比其较小的元素位置
                res[i][0] = -1
            } else {
                // 栈不为空,此时栈顶就是离i最近的较小元素位置
                res[i][0] = stack.last!
            }
            stack.append(i)
        }

        // 原理同上
        // 清空栈,倒序保持单调递增,确定i右侧最近较小值位置
        stack.removeAll()
        for i in (0 ..< count).reversed() {
            while !stack.isEmpty && nums[stack.last!] >= nums[i] {
                stack.removeLast()
            }

            if stack.isEmpty {
                res[i][1] = -1
            } else {
                res[i][1] = stack.last!
            }
            stack.append(i)
        }
        return res
    }
}