/*题目描述:假设打乱顺序的一群人站成一个队列。每个人由一个整数对(h,k)表示,其中h是这个 人的身高,k是排在这个人前面而且身高大于或等于h的人数。编写一个算法来重建这个队列。 示例: 输入:[[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]] 输出:[[5,0],[7,0],[5,2],[6,1],[4,4],[7,1] */ /* 思路:当两个人的高度h相同时,k比较大的往后排;两个人高度不同时,“个子矮的”对于个子高的来说 是不可见的,默认人数为0;所以先根据高度(降序)和个数进行排序,此时people=[[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]],按照k值插入到索引index=k的地方,index之后的往后移 */
Go语言实现
package main
import "fmt"
import "sort"
func ReconstructQueue(people [][]int)[][]int{
//排序,先按照身高h进行排序,如果身高一样高,那就按照人数k排序
sort.Slice(people,func(i,j int) bool{
return (people[i][0]>people[j][0])||(people[i][0]==people[j][0]&&people[i][1]<people[j][1])
})
//此时people=[[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]]
//按照k值插入到index=k的地方,index之后的往后移
for i,p:=range people{
copy(people[p[1]+1:i+1],people[p[1]:i+1]) //将index之后的复制到index+1
people[p[1]]=p //将p插入到index位置
}
return people
}
func main(){
fmt.Println("一日一力扣:根据身高重建队列")
people:=[][]int{{7,0},{4,4},{7,1},{5,0},{6,1},{5,2}}
result:=ReconstructQueue(people)
fmt.Println("result=",result)
}
C++实现
class Solution {
public:
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
vector<pair<int,int> > result;
sort(people.begin(),people.end(),[](const pair<int,int>& a,const pair<int,int>& b){
return a.first>b.first||a.first==b.first && a.second<b.second;
});
for(auto a:people){
result.insert(result.begin()+a.second,a);
}
return result;
}
};