2D peak finding algorithm in O(n) worst case time?

前端 未结 3 1520
心在旅途
心在旅途 2020-12-23 15:18

I was doing this course on algorithms from MIT. In the very first lecture the professor presents the following problem:-

A peak in a 2D array is a value such that al

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-23 15:46

    1. Let's assume that width of the array is bigger than height, otherwise we will split in another direction.
    2. Split the array into three parts: central column, left side and right side.
    3. Go through the central column and two neighbour columns and look for maximum.
      • If it's in the central column - this is our peak
      • If it's in the left side, run this algorithm on subarray left_side + central_column
      • If it's in the right side, run this algorithm on subarray right_side + central_column

    Why this works:

    For cases where the maximum element is in the central column - obvious. If it's not, we can step from that maximum to increasing elements and will definitely not cross the central row, so a peak will definitely exist in the corresponding half.

    Why this is O(n):

    step #3 takes less than or equal to max_dimension iterations and max_dimension at least halves on every two algorithm steps. This gives n+n/2+n/4+... which is O(n). Important detail: we split by the maximum direction. For square arrays this means that split directions will be alternating. This is a difference from the last attempt in the PDF you linked to.

    A note: I'm not sure if it exactly matches the algorithm in the code you gave, it may or may not be a different approach.

提交回复
热议问题