LeetCode-406题:身高重建队列

这篇博客介绍了如何通过给定每个人的身高h和排在其前面身高大于或等于h的人数k来重建队列。首先按照身高h降序和人数k升序排序,然后根据k值将元素插入到正确的位置,最终得到重建的队列。提供了Go语言和C++两种实现方式。
摘要由CSDN通过智能技术生成
/*题目描述:假设打乱顺序的一群人站成一个队列。每个人由一个整数对(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;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路上的追梦人

您的鼓励就是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值