1. 程式人生 > >[LeetCode]406. Queue Reconstruction by Height

[LeetCode]406. Queue Reconstruction by Height

[LeetCode]406. Queue Reconstruction by Height

題目描述

這裡寫圖片描述

思路

參考了答案解法
people:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
排序後:
[[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]]
然後從陣列people第一個元素開始,放入到陣列result中,放入的位置就是離result開始位置偏移了元素第二個數字後的位置。如下:
1.
people: [7,0]
插入到離開始位置偏移了0個距離的位置。
result: [[7,0]]
2.
people: [7,1]
插入到離開始位置偏移了1個距離的位置,即插入到[7,0]的後面。
result: [[7,0], [7,1]]
3.
people: [6,1]
插入到離開始位置偏移了1個距離的位置,即插入到[7,0]的後面。
result: [[7,0], [6,1], [7,1]]
4.
people: [5,0]
插入到離開始位置偏移了0個距離的位置,即插入到[7,0]的前面。
result: [[5,0], [7,0], [6,1], [7,1]]
5.
people: [5,2]
插入到離開始位置偏移了2個距離的位置,即插入到[7,0]的後面。
result: [[5,0], [7,0], [5,2], [6,1], [7,1]]
5.
people: [4,4]
插入到離開始位置偏移了4個距離的位置,即插入到[6,1]的後面。
result: [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

程式碼

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Solution {
public:
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        vector<pair<int, int>> res;
        sort(people.begin(), people.end(), [](pair<int
, int> a, pair<int, int> b) { return (a.first > b.first) || (a.first == b.first && a.second < b.second); }); for (auto p : people) res.insert(res.begin() + p.second, p); return res; } }; int main() { vector<pair<int
, int>
> people = { make_pair(7,0), make_pair(4,4), make_pair(7,1), make_pair(5,0), make_pair(6,1), make_pair(5,2) }, res; Solution s; res = s.reconstructQueue(people); for (auto p : res) { cout << p.first << ' ' << p.second << endl; } system("pause"); return 0; }