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

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

    This is the implementation for the idea provided by user1990169. Complexity being O(N^2).

    public class Solution {
            class Person implements Comparator{
                int height;
                int infront;
                public Person(){
    
                }
                public Person(int height, int infront){
                    this.height = height;
                    this.infront = infront;
                }
                public int compare(Person p1, Person p2){
                    return p1.height - p2.height;
                }
            }
    
            public ArrayList order(ArrayList heights, ArrayList infronts) {
               int n = heights.size();
               Person[] people = new Person[n];
               for(int i = 0; i < n; i++){
                   people[i] = new Person(heights.get(i), infronts.get(i));
               }
    
               Arrays.sort(people, new Person());
    
    
               Person[] rst = new Person[n];
               for(Person p : people){
                   int count = 0;
                   for(int i = 0; i < n ; i++){
                         if(count == p.infront){
                            while(rst[i] != null && i < n - 1){
                                i++;
                            }
                            rst[i] = p;
                            break;
                        }
                        if(rst[i] == null) count++;
                   }
    
                }
                ArrayList heightrst = new ArrayList();
                for(int i = 0; i < n; i++){
                    heightrst.add(rst[i].height);
                }
                return heightrst;
            }
        }
    

提交回复
热议问题