406_根据身高重建队列_数组_中等
我的思路是先看前面的比自己高的人个数进行排序,人个数相等下肯定个子小的在前面,依次类推。
public int[][] reconstructQueue(int[][] people) { int index = 0; //表示已经排好的人数 int[][] queue = new int[people.length][2]; int flag[] = new int[people.length]; while (true) { if (index == 0) { int min = Integer.MAX_VALUE; int place = 0; for (int i = 0; i < queue.length; i++) { if (people[i][1] == 0 && people[i][0] < min) { queue[0][0] = people[i][0]; queue[0][1] = people[i][1]; place = i; min = people[i][0]; } } flag[place] = 1; index++; } else { int place = 0; int min = Integer.MAX_VALUE; //获取满足条件的身高最小值 for (int i = 0; i < people.length; i++) { if (flag[i] == 0 && min > people[i][0]) { int num = 0;//比我高的 for (int j = 0; j < index; j++) { if (queue[j][0] >= people[i][0]) { num++; if (num > people[i][1]) break; } } if (num == people[i][1]) { queue[index][0] = people[i][0]; queue[index][1] = people[i][1]; place = i; min = people[i][0]; } } } flag[place] = 1; index++; } if (index >= people.length) break; } // for (int i = 0; i < queue.length; i++) { // // System.out.print(queue[i][0]); // System.out.print(" "); // System.out.println(queue[i][1]); // // } return queue; }
官网的思路大致相同先是对身高进行排序,认为身高越高的在前面的可能性更大,身高相同则比自己高的个数多的再后,之后进行判断排序,比自己高的数量相等下个子低会插到前面,注意二维数组的排序方法。
public int[][] reconstructQueue1(int[][] people){ Arrays.sort(people, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { if(o1[0] != o2[0]){ return o2[0] - o1[0]; }else{ return o1[1] - o2[1]; } } }); ArrayList<int []> list = new ArrayList<>(); for (int i = 0; i < people.length; i++) { if(list.size()==people[i][1]){ list.add(people[i]); }else{ list.add(people[i][1],people[i]); } } int [][] Array = new int[people.length][2]; for (int i = 0; i < people.length; i++) { Array[i] = list.get(i); } return Array; }
作者:你的雷哥
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
· 零经验选手,Compose 一天开发一款小游戏!
2020-09-27 损失函数softmax_cross_entropy、binary_cross_entropy、sigmoid_cross_entropy之间的区别与联系
2020-09-27 sklearn——CountVectorizer详解
2020-09-27 命名实体识别