目录
解题思路:
关键在于“排序”。每个人由(h, k)组成,h代表身高,k代表在他前面身高大于等于他自己的人数。
排序规则:首先按照每个人的高度h降序排列,若两个人的高度h相等,则再按k升序排列。
Example 1
Input:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]Sort based on height and K value.
[[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]]Now we construct the queue using the sorted person list .
1. Add [7, 0] at index 0 --> [[7,0]] 2. Add [7, 1] at index 1 --> [[7,0], [7,1]] 3. Add [6, 1] at index 1 --> [[7,0], [6, 1, [7,1]] 4. Add [5, 0] at index 0 --> [[5,0], [7,0], [6, 1], [7,1]] 5. Add [5, 2] at index 2 --> [[5,0], [7,0], [5, 2], [6, 1], [7,1]] 6. Add [4, 4] at index 4 --> [[5,0], [7,0], [5, 2], [6, 1],[4, 4], [7,1]] which is output
C++解法一:
没有用到额外的辅助空间,但效率较低,因为一直在pepple这个vector中进行erase(删除)、insert(插入)导致时间效率较低。
class Solution {
public:
static bool compare(vector<int>& a, vector<int>& b){
return a[0] > b[0] || (a[0] == b[0] && a[1] < b[1]);
}
vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
//两种sort写法
//sort(people.begin(), people.end(), compare);
sort(people.begin(), people.end(), [](vector<int>& a, vector<int>& b) {
return a[0] > b[0] || (a[0] == b[0] && a[1] < b[1]);
});
vector<vector<int>> result;
for(int i = 0; i < people.size(); i++){
auto p = people[i];
//result.insert(result.begin() + p[1], p);
if(p[1] != i){
people.erase(people.begin() + i);
people.insert(people.begin() + p[1], p);
}
}
return people;
}
};
C++解法二:
时间效率比上面高,借助了辅助空间vector。
vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
sort(people.begin(), people.end(), [](vector<int>& a, vector<int>& b) {
return a[0] > b[0] || (a[0] == b[0] && a[1] < b[1]);
});
vector<vector<int>> result;
for(int i = 0; i < people.size(); i++){
auto p = people[i];
result.insert(result.begin() + p[1], p);
}
return result;
}
Python解法:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people.sort(key=lambda p:(-p[0], p[1]))
result = []
for p in people:
result.insert(p[1], p)
return result
Java解法:
public int[][] reconstructQueue(int[][] people) {
// sort array using Arrays.sort with custom comparator
Arrays.sort(people, (p1, p2) -> p1[0] == p2[0] ? p1[1] - p2[1] : p2[0] - p1[0]);
List<int[]> list = new ArrayList<>();
for (int i = 0; i < people.length; i++) {
list.add(people[i][1], people[i]); // placing people based on the K value
}
return list.toArray(people); // convert list to array
}
本小白华中科技大学在读研究生,自然语言处理方向。现每日一更LeetCode Top 100 Liked Questions, 旨在于通过通俗易懂的画风和诸位计算机朋友们一起成长呀,不局限某题,争取举一反三,所有Questions均呈上C++和Java解法,不足之处多多指正,共同学习。