Interview - Find magnitude pole in an array

前端 未结 8 2246
孤独总比滥情好
孤独总比滥情好 2021-02-09 15:52

Magnitude Pole: An element in an array whose left hand side elements are lesser than or equal to it and whose right hand side element are greater than or equal to it.

8条回答
  •  失恋的感觉
    2021-02-09 16:40

    • Create two bool[N] called NorthPole and SouthPole (just to be humorous.
    • step forward through A[]tracking maximum element found so far, and set SouthPole[i] true if A[i] > Max(A[0..i-1])
    • step backward through A[] and set NorthPole[i] true if A[i] < Min(A[i+1..N-1)
    • step forward through NorthPole and SouthPole to find first element with both set true.

    O(N) in each step above, as visiting each node once, so O(N) overall.

提交回复
热议问题