public class Solution {
public int[,] ReconstructQueue(int[,] people) {
if (people == null || people.Length == )
{
return new int[,] { };
} var row = people.GetLength();//二元组个数
var col = people.GetLength();// var dic = new Dictionary<int, List<int>>(); var ary = new int[row, col]; //将前面为0的“队头”确定
for (int i = ; i < row; i++)
{
var height = people[i, ];
var position = people[i, ]; if (!dic.ContainsKey(position))
{
var po = new List<int>();
po.Add(height);
dic.Add(position, po);
}
else
{
dic[position].Add(height);
}
} //先确定队头
var headlist = dic[].OrderBy(x => x).ToList();
for (int i = ; i < headlist.Count; i++)
{
ary[i, ] = headlist[i];
ary[i, ] = ;
}
//按照positon进行插入排序
var plist = dic.Keys.OrderBy(x => x).ToList(); var dtcount = dic[].Count;//队头的二元组数量 foreach (var p in plist)
{
if (p == )
{
continue;
}
var addlist = dic[p].OrderBy(x => x).ToList(); for (int i = ; i < addlist.Count; i++)//循环剩余的列表
{
var curheight = addlist[i];
var curposition = p; var cf = ;//队头中满足条件的数量
var inserted = false;//是否已经插入
for (int j = ; j < dtcount; j++)//循环队头,找到第一个不满足的位置
{
if (curheight <= ary[j, ])
{
cf++;//发现一个,比当前元素相等或更高的元素
if (cf > p)
{
//找到了不满足的情况,当前的j为插入的位置 //j以及j之后的元素都向后移动
for (int k = dtcount - ; k >= j; k--)
{
ary[k + , ] = ary[k, ];
ary[k + , ] = ary[k, ];
}
ary[j, ] = curheight;
ary[j, ] = curposition; inserted = true;
dtcount++;
break;
}
}
} if (!inserted)//没有遇到冲突的情况,插入末尾
{
ary[dtcount, ] = curheight;
ary[dtcount, ] = curposition;
dtcount++;
} } }
return ary;
}
}
https://leetcode.com/problems/queue-reconstruction-by-height/#/description
上面这个写的够长的了,用python,4行就可以实现:
class Solution:
def reconstructQueue(self, people):
res = []
for i in sorted(people, key = lambda x: (-x[0],x[1])):
res.insert(i[1], i)
return res
先按照第一个元素倒序排,再按照第二个元素正序排,然后用insert方法,在指定的index上插入。