您的位置:首页 > 产品设计 > UI/UE

leetcode——Queue Reconstruction by Height

2016-11-03 00:13 344 查看
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]]


解析:通过观察可以发现规律,h相同的子序列按k从小到大排列,因此可以先将队列按按k从小到大的顺序排列,之后逐个将队列中的元素插入到返回队列中,而插入位置则是位于当前返回队列的第k+1个高度大于等于h的元素前,倘若没有这样的元素,则位于队尾。时间复杂度为O(n^2),代码如下:

class Solution {
public:
static bool cmp(pair<int, int>& a, pair<int, int>&b)
{
return a.second < b.second;
}
vector<pair<int, int> > reconstructQueue(vector<pair<int, int> >& people) {
vector<pair<int, int> >	ans;
int n = people.size(), i, j, num;
if(!n)	return ans;
sort(people.begin(), people.end(), cmp);
ans.push_back(people[0]);
for(i=1; i<n; i++)
for(num=0,j=0; j<=ans.size(); j++)
{
if(j < ans.size() && ans[j].first >= people[i].first)	num ++;
if(num > people[i].second || j == ans.size())
{
ans.insert(ans.begin() + j, people[i]);
break;
}
}
return ans;
}
};


-------------------------------------------------------------------------------------------------

上述算法只是将people队列按k的大小进行排序,如果同时根据h以及k进行排序则问题变得更加简单。考虑如果h相同,则队列按k从小到大排列,于是如果最先将队列中h最大的子序列加入返回队列中,则序列势必按照k进行排列,然后加入h次大的子序列,则对于元素i,h大于等于i的h或者h相同且k小于i的k 的元素都在当前队列内,并都将排列在i之前,故元素i的k即是其插入的位置。按此算法时间复杂度等于排序时间复杂度,即为O(nlogn)。

class Solution {
public:
static bool cmp(pair<int, int>& a, pair<int, int>&b)
{
return (a.first > b.first || (a.first == b.first && a.second < b.second));
}
vector<pair<int, int> > reconstructQueue(vector<pair<int, int> >& people) {
vector<pair<int, int> >	ans;
int n = people.size(), i, j, num;
if(!n)	return ans;
sort(people.begin(), people.end(), cmp);
for(i=0; i<n; i++)
ans.insert(ans.begin() + people[i].second, people[i]);
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息