题目: https://leetcode.cn/problems/queue-reconstruction-by-height/
程序的结构如下,
CMakeLists.txt
cmake_minimum_required(VERSION 2.6)
project(queue_reconstruction_by_height)
set(CMAKE_CXX_STANDARD 20)
add_definitions(-g)
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../include)
string(REPLACE ".cpp" "" file "main.cpp")
add_executable(${file} "main.cpp")
main.cpp
#include "printer/printer.hpp"
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
// 排序规则,身高较高的放在后面,
// 当身高相同的时候,排序较大的放在前面
sort(people.begin(), people.end(), [](vector<int> const& u, vector<int> const& v){
return u[0] < v[0] || (u[0] == v[0] && u[1] > v[1]);
});
int n = people.size();
vector<vector<int>> ans(n);
for(auto const& person: people) {
// 计算当前元素的space位置数,+1是为了防止减出负数来
int spaces = person[1] + 1;
// 在链表中的空位中插值,按照 spaces所在的位置插
for(int i=0; i<n; ++i) {
if(ans[i].empty()) {
--spaces;
// 说明当前已经循环到spaces位置了
if(!spaces) {
// 插值,退出
ans[i] = person;
break;
}
}
}
}
return ans;
}
};
auto main(int argc, char** argv) -> int {
Solution s;
vector<vector<int>> people {{7,0},{4,4},{7,1},{5,0},{6,1},{5,2}};
auto ans = s.reconstructQueue(people);
cout << people << "\n is reconstructed to the below queue: \n";
cout << ans << "\n";
return EXIT_SUCCESS;
}
include/printer/printer.hpp
#ifndef _FREDRIC_PRINTER_HPP_
#define _FREDRIC_PRINTER_HPP_
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
using std::ostream;
using std::stringstream;
using std::vector;
using std::string;
/**
* Function used to print vector of vectors
* */
template<typename T>
ostream& operator<<(ostream& os, vector<vector<T>> const& points) {
stringstream ss;
for(auto v: points) {
stringstream inner_ss;
inner_ss << "[";
for(auto ele: v) {
inner_ss << ele << ",";
}
// 去掉最右边的逗号
string inner_str = inner_ss.str();
inner_str = inner_str.substr(0, inner_str.size()-1);
ss << inner_str;
ss << "],";
}
// 再次去掉最右边的逗号
string out_str = ss.str();
out_str = out_str.substr(0, out_str.size()-1);
return os << out_str;
}
/**
* Function used to print a std::vector
*/
template <typename T>
ostream& operator<<(ostream& os, vector<T> const& eles) {
stringstream ss;
for(auto&& ele: eles) {
ss << ele << ",";
}
string res_str = ss.str();
res_str = res_str.substr(0, res_str.size()-1);
return os << res_str;
}
#endif
程序输出如下,