Description
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]]
簡要題解:
這道題總的解題方向是採用貪心算法。具體做法是不斷循壞people向量的各個元素直到該向量爲空。每次從people中取出一個,在result中找到一個剛好可以放的位置放入。如果找不到可以放的位置放就跳過這個元素,等待下一輪循壞再繼續找位置。
但是這樣做會有點問題,我們必須保證後放入result的元素不會影響到先放入result的元素。因此,需要對people中的每個人按身高大小由高到底排序。(身高較低的不管怎麼放都不會影響到身高較高的人)。還要注意到,對於兩個身高相同的情況,k值小的應該放在前面。因爲,身高相同的兩個人,在result中k值小的一定是放在k值較大的那個人的前面。也就是說,在身高相同的情況下,k值較小的可能會影響k值較大的那個人。排完序後,就採用前面說的那種貪心算法來構造result就可得到正確的結果。
代碼:
class Solution {
public:
static vector<pair<int, int> > reconstructQueue(vector<pair<int, int> >& people) {
vector<pair<int, int> > result;
for (int i = 0; i < people.size(); i++)
for (int j = i + 1; j < people.size(); j++)
if ((people[i].first < people[j].first) ||
(people[i].first == people[j].first && people[i].second > people[j].second)) {
pair<int, int> temp = people[i];
people[i] = people[j];
people[j] = temp;
}
while (!people.empty()) {
vector<pair<int, int> >::iterator iter1, iter2;
for (iter1 = people.begin(); iter1 != people.end(); iter1++) {
int count = 0;
int flag = false;
for (iter2 = result.begin(); iter2 != result.end(); iter2++) {
if (count == iter1->second + 1) {
iter2--;
result.insert(iter2, *iter1);
people.erase(iter1);
flag = true;
break;
}
if (iter2->first >= iter1->first)
count++;
}
if (!flag && count == iter1->second + 1) {
pair<int, int> temp = result[result.size()-1];
result[result.size()-1] = *iter1;
result.push_back(temp);
people.erase(iter1);
flag = true;
}
if (!flag && count == iter1->second) {
result.push_back(*iter1);
people.erase(iter1);
flag = true;
}
if (flag)
break;
}
}
return result;
}
};