LeetCode 406. Queue Reconstruction by Height C++

406. Queue Reconstruction by Height

Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue.

Note:
The number of people is less than 1,100.

Example

Input:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]

Output:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

Approach

  1. 题目大意是,要求重新整理队伍,每组带有身高和前面身高大于或等于他的人的数量。遇到这个问题我一般会想到排序,然后这道题的关键也确实是排序,排序排得好,代码写的少。我首先按每个人得身高由大到小进行排序,身高相等则按另一个数小的优先。然后我们开辟一个空的队列,长度一样,仔细思考,就会知道,每个人的位置已经可以确定了,因为任意一个人,他后边的人身高都是大于等于他的,所以他只要根据他第二个数计算新队列从第一位开始有多少个空位(因为后边空位只要被补齐,那么这个空位的人还是高于他)或者高于他的人的数量,该数量等于它第二个数的时候就是他的位置。44ms

Code

class Solution {
public:
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        int N = people.size();
        sort(people.begin(), people.end(), cmp);
        vector<pair<int, int>>ans(N,make_pair(0,0));
        for (int i = 0; i < N; i++) {
            int need = people[i].second>0?people[i].second+1:0;
            int high = people[i].first;
            for (int j = 0; j < N; j++) {
                if (need == 0) {
                    if (ans[j].first == 0) {
                        ans[j] = people[i];
                        break;
                    }
                }
                else if (need>0&&(ans[j].first == 0 || ans[j].first >= high)) {
                    need--;
                    if (need == 0) {
                        ans[j] = people[i];
                        break;
                    }
                }
            }
        }
        return ans;
    }
};

Again

  1. 看了其他人提交的代码,果然排序排的好,代码写的少,思路都差不多,不过他是身高高的在前,直接上代码。24ms
bool cmp(const pair<int, int>&a, const pair<int, int> &b) {
    if (a.first == b.first)return a.second < b.second;
    return a.first > b.first;
}
class Solution {
public:
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        int N = people.size();
        sort(people.begin(), people.end(), cmp);
        vector<pair<int, int>>ans;
        for (int i = 0; i < N; i++) {
            ans.insert(ans.begin()+people[i].second, people[i]);
        }
        return ans;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值