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

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

    Was solving this problem today, here is what I came up with:

    The idea is to sort the heights array in descending order. Once, we have this sorted array - pick up an element from this element and place it in the resultant array at the corresponding index (I am using an ArrayList for the same, it would be nice to use LinkedList) :

    public class Solution {
        public ArrayList order(ArrayList heights,      ArrayList infronts) {
            Person[] persons = new Person[heights.size()];
            ArrayList res = new ArrayList<>();
    
            for (int i = 0; i < persons.length; i++) {
                persons[i] = new Person(heights.get(i), infronts.get(i));
            }
    
            Arrays.sort(persons, (p1, p2) ->  {
                return Integer.compare(p2.height, p1.height);
            });
    
            for (int i = 0; i < persons.length; i++) {
                //System.out.println("adding "+persons[i].height+" "+persons[i].count);
                res.add(persons[i].count, persons[i].height);
            }
    
            return res;
        }
    
    
        private static class Person {
            public final int height;
            public final int count;
    
            public Person(int h, int c) {
                height = h;
                count = c;
            }
        }
    }
    

提交回复
热议问题