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 700
囚心锁ツ
囚心锁ツ 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:28

    Your stack approach is correct. It works because if you pop an element bigger than A[i], that element will never be needed for any elements following A[i], because you can just use A[i] instead.

    Each element is only accessed twice, so this is O(n).

提交回复
热议问题