Queue Reconstruction by Height

本文介绍了一种基于贪心策略的队列重构算法,用于解决特定条件下的序列恢复问题。该算法通过两次排序和插入操作,高效地解决了高度与顺序约束的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue.

Note:
The number of people is less than 1,100.

Example

Input:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]

Output:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

分析

    这是leetcode中被归类为Greedy(贪心)标签的一道中等难度题,题意是恢复一个顺序被打乱的序列。序列中每个元素是一个pair<int,int>类型的变量,first代表身高,second代表排在他之前的人中不矮于他的人的个数。


    从贪心的角度出发,很明显先安排号个高者的相对顺序是可取的,因为他们影响了个矮者的位置。在安排同一身高人的顺序时优先安排second较小的人。


    所以首先将被打乱的序列做一个排序,个高者排在前面,身高相同时second小者排在前面。然后从第二个元素开始再对配个元素作出调整,如某个元素(h,k)应该插入第k个位置。


    算法复杂度为O(n)。

代码

class Solution {
public:
    vector<pair<int, int> > reconstructQueue(vector<pair<int, int> >& people) {
        vector<pair<int, int> > ans = people;
        int n = ans.size();
        int i,j;
        pair<int,int> tmp;
        for (i = 1;i < n;i++)
        {
        	tmp = ans[i];
        	for (j = i - 1;tmp > ans[j] && j >= 0;j--)
        		ans[j+1] = ans[j];
        	ans[j+1] = tmp;
	}
		
	for (i = 1;i < n;i++)
	{
		tmp = ans[i];
		for (j = i - 1;j >= tmp.second;j--)
			ans[j + 1] = ans[j];
		ans[tmp.second]= tmp;
	}
		
	return ans;
    }
};





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值