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.

给一个数组,存的是pair(int h, int k)类型的,其中h表示高度,k表示数组中该数对前面的数对比该数对的h大的数量,要求按照数对对该数组进行重构

问题解决:

找的网上的算法

即首先对数组中的元素进行排序,对h从高到低排,若h相等,对k从低到高排

新建一个数组result

遍历排序后的原数组,一个一个数对取出来插入result,插入的偏移量为数对的k

代码如下:

class Solution {
public:
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        vector<pair<int, int>> result;
        vector<pair<int, int>>::iterator iter1 = people.begin();
        //排序
        sort(people.begin(), people.end(), sortPair);
        /*for(; iter1 != people.end(); iter1++) {
            vector<pair<int, int>>::iterator iter2 = result.begin();
            int i = (*iter1).second;
            if(i > result.size()) result.push_back(*iter1);
            else {
                while(i--) iter2++;
                result.insert(iter2, *iter1);
            }
        }*/
        //遍历排序后的数组并插入result
        for(auto p : people) {
            result.insert(result.begin()+p.second,p);
        }
        
        return result;
        
    }
    //排序函数
    static bool sortPair(const pair<int, int> &a, const pair<int, int> &b) {
        if(a.first > b.first) return true;
        if(a.first == b.first && a.second < b.second) return true;
        return false;
        
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值