Concise 6 lines Java solution


  • 0
    I
    public class Solution {
        public int[][] reconstructQueue(int[][] people) {
            Arrays.sort(people, (p1, p2) -> p1[0] != p2[0] ? p2[0] - p1[0] : p1[1] - p2[1]);
            List<int[]> temp = new ArrayList<>();
            for (int[] person : people) {
                temp.add(person[1], person);
            }
            return temp.toArray(new int[people.length][]);
        }
    }
    

  • 0
    Y

    I think your code would not work for [[7,0],[4,4],[7,2],[5,0],[6,1],[5,2]] input.


  • 0
    I

    @yaozk this is not a valid input. There are only two persons in your example with height of 7 or more. Thus it is not possible to have two other people in front of [7, 2].


  • 0
    Y

    @ivtoskov I see. However, you idea is great and your code is good, but id you add one more line will be saver. Your code add the person into the ArrayList index base on the k, but if k is larger than the ArrayList size the program will throw exception. So, I would add one more line to avoid this exception. Here is my code, same idea but one more line:

    public int[][] reconstructQueue(int[][] people) {
            Arrays.sort(people,new Comparator<int[]>(){
               public int compare(int[] o1, int[] o2){
                   return o1[0]!=o2[0]?-o1[0]+o2[0]:o1[1]-o2[1];
               }
            });
            List<int[]> res = new ArrayList<int[]>();
            for(int[] cur : people){
            	if (cur[1] >= res.size()) res.add(cur);
            	else 	res.add(cur[1],cur);       
            }
            return res.toArray(new int[people.length][]);
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.