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