Leetcode Queue Reconstruction by Height

题意:给出每个人的身高和前面高于或者等于自己身高的人的个数,重排列这个队伍。

思路:先从身高较高的人入手,因为他们的限制是最小的,在他们中间插入身高较矮的人对结果没有影响。因此先将他们按身高降序排序,如果身高一样则按人数升序排序。最后一个一个插入,人数即是他们在队列中的新位置。

顺序遍历插入:

class Solution {
public:
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        vector<pair<int, int> > re;
        std::sort(people.begin(), people.end(), [](pair<int, int> a, pair<int, int> b) {if(a.first == b.first) return a.second < b.second; else return a.first > b.first;});
        
        for(int i = 0; i < people.size();++ i) {
            std::vector<pair<int, int>>::iterator it;
            it = re.begin();
            int count = 0;
            while(it != re.end()) {
                if(count == people[i].second) break;
                if(people[i].first <= it->first) count ++;
                it ++;
            }
            if(it == re.end()) re.push_back(people[i]);
            else re.insert(it, people[i]);
        }
        
        return re;
    }
};
立即插入:

class Solution {
public:
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        vector<pair<int, int> > re;
        std::sort(people.begin(), people.end(), [](pair<int, int> a, pair<int, int> b) {if(a.first == b.first) return a.second < b.second; else return a.first > b.first;});
        
        for(int i = 0; i < people.size();++ i) {
            std::vector<pair<int, int>>::iterator it;
            it = re.begin() + people[i].second;
            
            if(it == re.end()) re.push_back(people[i]);
            else re.insert(it, people[i]);
        }
        
        return re;
    }
};


猜你喜欢

转载自blog.csdn.net/markpen/article/details/54561847