【面试题三】求一个数组中右边第一个比他大的数(单调栈)

def find_near_max(array):
    if not array:
        return []
    stack = []
    res_arr = [-1] * len(array)
    for i in range(len(array)):
        while stack and array[stack[-1]] < array[i]:
            res_arr[stack[-1]] = array[i]
            stack.pop()
        stack.append(i)
    print(res_arr)
    return res_arr


if __name__ == '__main__':
    arr1 = [2, 1, 3, 4]
    arr2 = [3, 5, 6, 4, 5]
    arr3 = [6, 3, 5, 8, 1]
    res = find_near_max(arr3)

 

你可能感兴趣的:(数据结构与算法)