题目
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;
}
};