Skip to content

Commit c60d4a3

Browse files
authored
Create QueueReconstructionByHeight.java
1 parent 1dbbe06 commit c60d4a3

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

QueueReconstructionByHeight.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import java.util.ArrayList;
2+
class Solution {
3+
public int[][] reconstructQueue(int[][] people) {
4+
/*
5+
Algorithm:
6+
First sort all the people in decreasing order of their height.for those wo have same height sort them
7+
in ascending order of their k values
8+
Now simply iterate over the sorted array and insert them in the output array at kth index;
9+
10+
*/
11+
12+
Arrays.sort(people,(a,b) -> a[0]==b[0] ? a[1]-b[1] : b[0]-a[0]); // this means we will sort arrays based
13+
//on lambda expresiion/comparator a and b if a[0]==b[0] then we are going to return a[1]-b[1] else
14+
// we will return b[0]-a[0];
15+
16+
// creating a arraylist
17+
ArrayList<int[]> result = new ArrayList<>();
18+
// iterating in the array and putting them at index k
19+
for(int [] p : people){ // for each loop
20+
result.add(p[1],p); // p[1] = kth index
21+
}
22+
// returning the arraylist converting into array
23+
int ans[][] = result.toArray(new int[people.length][2]);
24+
25+
return ans;
26+
27+
}
28+
}

0 commit comments

Comments
 (0)