Leetcode 406. Queue Reconstruction by Height[Medium]

原題地址

題目内容

这里写图片描述

題目分析

题目的主要意思为,给你一串数组,让你对其进行“排序”,每个元素由两个值构成(a,b),a代表这个字符的大小,b代表有多少个比他大或者等于他的数字排在他前面,这就是最后生成的数组需要满足的条件。
首先我们可以对数组按照a进行从大到小的排序,如果a相同的话,就按照b来排,按照题目的要求,应该是b小的排在前面。定义一个结果数组res,排好序的数组在这个res里面的顺序,就是b的值的大小了
比如此時的順序為:
[[7,0], [7,1] , [6,1] , [5,0]] , [5,2] , [4,4] ]
那么首先插入[7,0]在res[0]的位置,[7,1]在res[1],
[6,1]由于b是1,那么他就在res[1],此时[7,1]向后挪一位,所以res=[[7,0],[6,1],[7,1]]
接著是[5,0]因為b=0,所以他插在res[0]的位置,以此类推。
主要是參考了discuss

代碼實現

class Solution {
public:
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        for(int i = 0; i < people.size(); i++){
            for(int j = 0; j < people.size(); j++){
                if(people[i].first > people[j].first ||
                   (people[i].first == people[j].first && people[i].second < people[j].second) ){
                    pair<int,int> temp;
                    temp = people[i];
                    people[i] = people[j];
                    people[j] = temp;
                }
            }
        }
        vector< pair<int,int> > res;
        for(int i = 0; i < people.size(); i++){
            res.insert(res.begin()+people[i].second,people[i]);
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/YuMingJing_/article/details/78867338