Interview - Find magnitude pole in an array

前端 未结 8 2274
孤独总比滥情好
孤独总比滥情好 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:39

    For an O(n) algorithm:

    1. Count the largest element from n[0] to n[k] for all k in [0, length(n)), save the answer in an array maxOnTheLeft. This costs O(n);
    2. Count the smallest element from n[k] to n[length(n)-1] for all k in [0, length(n)), save the answer in an array minOnTheRight. This costs O(n);
    3. Loop through the whole thing and find any n[k] with maxOnTheLeft <= n[k] <= minOnTheRight. This costs O(n).

    And you code is (at least) wrong here:

    if (A[i] > left_max && A[i] <= right_min) // <-- should be >= and <=
    

提交回复
热议问题