1. Convert 2D array to people list
2. Customize a Comparator to sort the people list, which ensure people with lower k should be in the front of the queue + in the case of same k for multiple people, lower h people should be in the front of the queue. After each sort, people with lowest k and h will be at the head of the queue.
3. Add the head of sorted list to result set.
4. Remove the head from sorted list.
5. Update k in the remaining list. People with h lower or equal to the removed head need to decrease the k by 1.
6. Inorder to store the original k (when adding result, original k is needed), introduce a new element for people. Value of which is the original k.
public class Solution {
public int[][] reconstructQueue(int[][] people) {
List<int[]> list = new ArrayList<int[]>();
for(int i=0; i<people.length; i++){
int[] curPeople = new int[]{people[i][0], people[i][1], people[i][1]};
list.add(curPeople);
}
int[][] ans = new int[people.length][];
for(int i=0; i<people.length; i++){
Collections.sort(list, new Comparator<int[]>(){
public int compare(int[] a, int[] b){
if(a[1]==b[1]){
return a[0]-b[0];
}
return a[1]-b[1];
}
});
int[] head = list.get(0);
ans[i] = new int[]{head[0], head[2]};
list.remove(0);
for(int[] curPeople: list){
if(curPeople[0]<=ans[i][0]){
curPeople[1]-=1;
}
}
}
return ans;
}
}