Puzzle: Find the order of n persons standing in a line (based on their heights)

前端 未结 11 2190
抹茶落季
抹茶落季 2020-12-30 05:58

Saw this question on Careercup.com:

Given heights of n persons standing in a line and a list of numbers corresponding to each person (p) that gives the number of pers

11条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-30 06:19

    The O(nlogn) algoritm is possible.

    First assume that all heights are different.

    Sort people by heights. Then iterate from shortest to tallest. In each step you need an efficient way to put the next person to the correct position. Notice that people we've already placed are not taller that the current person. And the people we place after are taller than the current. So we have to find a place such that the number of empty positions in the front is equal to the inFronts value of this person. This task can be done using a data structure called interval tree in O(logn) time. So the total time of an algorithm is O(nlogn).

    This algorithm works well in case where there's no ties. As it may be safely assumed that empty places up to front will be filled by taller people.

    In case when ties are possible, we need to assure that people of the same height are placed in increasing order of their positions. It can be achieved if we will process people by non-decreasing inFronts value. So, in case of possible ties we should also consider inFronts values when sorting people.

    And if at some step we can't find a position for next person then the answer it "it's impossible to satisfy problem constraints".

提交回复
热议问题