https://leetcode.com/problems/queue-reconstruction-by-height/
Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers \$(h, k)\$, where \$h\$ is the height of the person and \$k\$ is the number of people in front of this person who have a height greater than or equal to \$h\$. Write an algorithm to reconstruct the queue.
Note: The number of people is less than 1,100.
Example Input: [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] Output: [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
Please review for performance
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
namespace SortingQuestions
{
/// <summary>
/// https://leetcode.com/problems/queue-reconstruction-by-height/
/// </summary>
[TestClass]
public class ReconstructQueueTest
{
[TestMethod]
public void ReconstructQueueExampleTest()
{
int[][] people = new int[6][];
people[0] = new[] { 7, 0 };
people[1] = new[] { 4, 4 };
people[2] = new[] { 7, 1 };
people[3] = new[] { 5, 0 };
people[4] = new[] { 6, 1 };
people[5] = new[] { 5, 2 };
int[][] expected = new int[6][];
expected[0] = new[] { 5, 0 };
expected[1] = new[] { 7, 0 };
expected[2] = new[] { 5, 2 };
expected[3] = new[] { 6, 1 };
expected[4] = new[] { 4, 4 };
expected[5] = new[] { 7, 1 };
int[][] res = ReconstructQueueClass.ReconstructQueue(people);
for (var index = 0; index < res.Length; index++)
{
CollectionAssert.AreEqual(expected[index], res[index]);
}
}
}
public class ReconstructQueueClass
{
public static int[][] ReconstructQueue(int[][] people)
{
int[][] res = new int[people.Length][];
Array.Sort(people, new PairComparer());
List<int> list = new List<int>();
for (int i = 0; i < people.Length; i++)
{
list.Add(i); //a list of indices 0,1,2,3,4...
res[i] = new int[2];
}
for (int i = 0; i < people.Length; i++)
{
int index = list[people[i][1]]; //the index in the result is the number of people before you
res[index][0] = people[i][0];
res[index][1] = people[i][1];
list.RemoveAt(people[i][1]); // we remove the index from the list so we keep only the un used ones
}
return res;
}
}
/// <summary>
/// sort the people, have min height first
/// for the same height for example 5,0 and 5,2
/// 5,2 is before 5,0
/// </summary>
public class PairComparer : IComparer<int[]>
{
public int Compare(int[] x, int[] y)
{
if (x[0] != y[0])
{
return x[0] - y[0];// we want min value first
}
return y[1] - x[1];
}
}
}