[LeetCode]406. Queue Reconstruction by Height

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Lcharon/article/details/75579496

[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;
}

猜你喜欢

转载自blog.csdn.net/Lcharon/article/details/75579496