Given an array A,compute B s.t B[i] stores the nearest element to the left of A[i] which is smaller than A[i]

前端 未结 3 699
囚心锁ツ
囚心锁ツ 2021-01-12 16:29

Given an array A[1..n], we want to compute another array B[1..n] such that B[i] stores the nearest element to the left of A[i]

3条回答
  •  不知归路
    2021-01-12 17:05

    B[1]=A[1]
    push(B[1])
    for i=2 to n do
    {
        while(A[i] > stack_top ANS stack_top!=NULL)
           pop()
        if(stack_top=NULL)
            B[i]=A[i]
        else
            B[i]=stack_top
        push(A[i])
    }
    

    As IVlad pointed out that each element is pushed and poped atmost once, time is O(n).

    pl do correct me if there is some mistake, and I am curious for any alternate solution which avoids stack and is cheaper.

提交回复
热议问题