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

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

    Simple O(n^2) solution for this in Java:

    Algorith:

    1. If the position of the shortest person is i, i-1 taller people will be in front of him.
    2. We fix the position of shortest person and then move to second shortest person.
    3. 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.
    4. We can optimise this solution even more by using segment tree. See this link.

      class Person implements Comparable{
          int height;
          int pos;
      
          Person(int height, int pos) {
              this.height = height;
              this.pos = pos;
          }
      
          @Override
          public int compareTo(Person person) {
              return this.height - person.height;
          }
      }
      
      public class Solution {
          public int[] order(int[] heights, int[] positions) {
              int n = heights.length;
              int[] ans = new int[n];
              PriorityQueue pq = new PriorityQueue();
              for( int i=0; i person.pos) break;
                      index++;
                  }
                  ans[index] = person.height;
              }
              return ans;
          }
      }
      

提交回复
热议问题