[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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值