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

前端 未结 11 2214
抹茶落季
抹茶落季 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:34

    I think one approach can be the following. Although it again seems to be O(n^2) at present.

    Sort the Height array and corresponding 'p' array in ascending order of heights (in O(nlogn)). Pick the first element in the list. Put that element in the final array in the position given by the p index.

    For example after sorting,
    H - 1, 2, 3, 4, 5, 6
    p - 3, 2, 1, 2, 0, 0.

    1st element should go in position 3. Hence final array becomes:
    ---1--

    2nd element shall go in position 2. Hence final array becomes:
    --21--

    3rd element should go in position 1. Hence final array becomes:
    -321--

    4th element shall go in position 2. This is the position among the empty ones. Hence final array becomes:
    -321-4

    5th element shall go in position 0. Hence final array becomes:
    5321-4

    6th element should go in position 0. Hence final array becomes:
    532164

提交回复
热议问题