LeetCode 406 Queue Reconstruction by Height

来源:互联网 发布:淘宝服装的平铺和挂拍 编辑:程序博客网 时间:2024/05/17 23:28

题目

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

解法

按照k的大小升序排列,如果k相等就按h升序排列。
对每一个元素people[i],计算从0到i位置中的元素的h大于等于people[i]的h的个数,直到计数比people[i]的k大为止,如果位置停在i前,说明people[i]需要移动,将people[i]插入到停止位置。
对于样例[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
排序后的结果为:[[5,0], [7,0], [6,1], [7,1], [5,2], [4,4]]
位置调整过程:
[[5,0], [7,0], [6,1], [7,1], [5,2], [4,4]]
[[5,0], [7,0], [5,2], [6,1], [7,1], [4,4]]
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

class Solution {public:    static bool Cmp_pair(const pair<int, int> &a, const pair<int, int> &b) {        if (a.second == b.second)            return a.first < b.first;        else            return a.second < b.second;    }    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {        sort(people.begin(),people.end(),Cmp_pair);        for(int i = 0; i < people.size(); i++) {            int count = 0;            for (int j = 0; j < i; j++) {                if (people[j].first > people[i].first || people[j].first == people[i].first)                    count++;                if (count > people[i].second) {                    pair<int,int> temp = people[j];                    people[j] = people[i];                    people[i] = temp;                }            }        }        return people;    }};

去网上看了下别人的算法,按照h降序排序,如果h相等则按照k升序排序。
对于样例[[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第一个元素开始,放入到数组ans中,每次只需要将元素插入到新数组的k的位置即可。
每次插入元素后的ans如下:
[[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]]

class Solution {public:    static bool Cmp_pair(const pair<int, int> &a, const pair<int, int> &b) {        if (a.first == b.first)            return a.second < b.second;        else            return a.first > b.first;    }    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {        sort(people.begin(),people.end(),Cmp_pair);        vector<pair<int, int>> ans;          for(auto val: people)              ans.insert(ans.begin() + val.second, val);          return ans;      }};
0 0
原创粉丝点击