题目是:406. 根据身高重建队列
题解:这题比较骚的是思路,想得到思路就没什么难题。题目给了我们两个信息,1 身高 2 比当前身高大的个数,所以怎么利用参数呢?
第一步:按身高降序,身高相同,按个数升序——目的是让高个子看不到挨个子;
第二部:将上面结果,按个数插入,正好就是我们要得结果。
不bb了,看代码:
python:
class Solution(object):
def reconstructQueue(self, people):
"""
:type people: List[List[int]]
:rtype: List[List[int]]
"""
# 先按身高降序
people.sort(key = lambda x : (- x[0], x[1]))
# print(people)
res = []
# 最骚的——按k插入
for i in people:
res.insert(i[1],i)
return res
c++
bool sortFunc(vector<int>& p, vector<int>& q) {
return (p[0] > q[0]) || (p[0] == q[0] && p[1] < q[1]);
}
class Solution {
public:
vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
vector<vector<int>> res;
sort(people.begin(),people.end(),sortFunc);
for(auto p : people) {
cout<<p[0]<<p[1]<<endl;
res.insert(res.begin() + p[1], p);
}
return res;
}
};