LeetCode解题报告 406. Queue Reconstruction by Height [medium]

题目描述

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]]

解题思路

首先对输入进行排序,因为是双关键词,所以不能直接用sort函数,需要重写sort。按pair的首位(first)为主码进行升序排序,如果first相同,再按second降序排列。
排序之后使用stl的insert函数进行插入,insert的用法为(position, value),如果要写成三个数字的话,第二位是重复插入的个数,(position,count,value)。
我们可以根据排序后的数组,来找到贪心的策略。
排序后的数组为:

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

来从[7,0]开始输出每次多加一个后的排列结果,可以清楚的发现规律:

[7,0]

[7,0],[7,1]

[7,0],[6,1],[7,1]

[5,0],[7,0],[6,1],[7,1]

[5,0],[7,0],[5,2],[6,1],[7,1]

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

可以发现,每次插入的位置都恰好是最新的初始位置+待插入的second值。


复杂度分析
时间复杂度为O(N)。

代码如下(完整的,包括main的测试):
#include <iostream>
#include <vector>
using namespace std;

class Solution {
private:
    static bool comp (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;
        //return a.first>b.first || (a.first == b.first && a.second < b.second);
    }
    
public:
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        vector<pair<int, int>>result;
        vector<int>::iterator it;
        sort(people.begin(), people.end(), comp);
        int n=people.size();
        for (int i=0; i<n ; i++){
            result.insert(result.begin()+people[i].second,people[i]);
            //cout << i << " :" << result[i].first << result[i].second << endl;
        }
        
        return people;
    }
};
int main(int argc, const char * argv[]) {
    vector<pair<int, int>>me;
    me.push_back(pair<int, int>(7,0));
    me.push_back(pair<int, int>(7,1));
    me.push_back(pair<int, int>(5,0));
    me.push_back(pair<int, int>(4,4));
    me.push_back(pair<int, int>(5,2));
    me.push_back(pair<int, int>(6,1));
    vector<pair<int, int>>out;
    Solution my;
    out=my.reconstructQueue(me);
    for (int i=0; i<me.size(); i++) {
        cout << out[i].first <<"," << out[i].second << endl;
    }
    
    
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值