มีรายการคนในคิวสุ่ม แต่ละคนแสดงด้วยคู่ตัวเลข (h, k) โดย h = ความสูง, k = จำนวนคนหน้าหน้าที่มีความสูงมากกว่าหรือเท่ากับ h ต้องเขียนอัลกอริทึมสร้างคิวใหม่ให้ถูกต้อง
ตัวอย่าง: อินพุต [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] ผลลัพธ์ควรเป็น:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
ตัวอย่างโค้ด
const arr = [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]];
const reconstructQueue = data => {
const result = [];
const sorter = (a, b) => b[0] - a[0] || a[1] - b[1];
data.sort(sorter);
for (let i = 0; i < data.length; i++) {
result.splice(data[i][1], 0, data[i]);
}
return result;
};
console.log(reconstructQueue(arr));
ผลลัพธ์
ค่าที่แสดงในคอนโซลจะเป็นดังนี้:
[ [ 5, 0 ], [ 7, 0 ], [ 5, 2 ], [ 6, 1 ], [ 4, 4 ], [ 7, 1 ] ]