首页 > 代码库 > leetcode406
leetcode406
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
leetcode406
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。