- leet:地址
- 问题描述:
- 有一打乱顺序的一群人站成一个队列。 每个人由一个整数对(h, k)表示,其中h是这个人的身高,k是排在这个人前面且身高大于或等于h的人数。 现需要按照该整数对(h,k)表示的要求 编写一个算法来重建这个队列以满足该要求。
- 输入输出样例:
- 输入: [[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升序排序来重构队列。
- 对重构出的序列按照插入排序的原则,将元素顺序地按照k值插入到结果队列中。
- 形象解释:
- Python代码1:
def reconstruct(people):
res, dic, height = [], {}, []
for i in range(len(people)):
p = people[i]
if p[0] in dic:
dic[p[0]].append((p[1], i))
else:
dic[p[0]] = [(p[1], i)]
height.append(p[0])
height.sort()
for h in height[::-1]:
dic[h].sort()
for p in dic[h]:
res.insert(p[0], people[p[1]])
#res.insert(p[0], (h, p[0]))
return res
- Python代码2:
class Solution(object):
def reconstructQueue(self, people):
"""
:type people: List[List[int]]
:rtype: List[List[int]]
"""
people = sorted(people, key = lambda x: (-x[0], x[1]))
res = []
for p in people:
res.insert(p[1], p)
return res
主调函数
if __name__ == "__main__":
#people_str = sys.argv[1] #[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
people_str = "[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]"
people = eval(people_str)
print("result is :" + str(reconstruct(people)))
print("ok")
- c++ 代码
- 代码重点:
- 比较函数中使用回调函数
- vector的insert函数的使用(有三种使用方式)。
- 代码重点:
class Solution
{
public:
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>> people)
{
auto comp = [](pair<int, int> a, pair<int, int> b)
{return a.first > b.first || (a.first == b.first && a.second < b.second); };
sort(people.begin(), people.end(), comp);
vector<pair<int, int>> res;
for (auto& p : people)
res.insert(res.begin() + p.second, p);
return res;
}
};
c++ 主调函数
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main(int argc, char* argv[])
{
vector<pair<int, int>> data = {make_pair(7,0), make_pair(4, 4), make_pair(7,1), make_pair(5, 0), make_pair(6, 1), make_pair(5, 2)};
Solution solution;
vector<pair<int, int>> res = solution.reconstructQueue(data);
for (auto p : res)
{
cout << "(" << p.first << "," << p.second << ")" << endl;
}
system("pause");
return 0;
}