Queue Reconstruction by Height

ㅋㅋ·2022년 6월 29일
0

알고리즘-leetcode

목록 보기
20/135

주어진 벡터를 데이터대로 정렬하는 문제이다.

데이터에는 사람의 키와 앞에 자신의 키보다 같거나 큰 사람이 몇명 있는지 쓰여있다.

벡터를 데이터가 만족하도록 정렬하면 된다.

class Solution {
public:
    vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
        
        sort(people.begin(), people.end(), 
            [](const auto &lhs, const auto &rhs)
            {
                if (lhs[0] > rhs[0])
                {
                    return true;
                }
                else if (lhs[0] == rhs[0] && (lhs[1] < rhs[1]))
                {
                    return true;   
                }
                
                return false;
            });
        
        list<vector<int>> queue(people.begin(), people.end());

        int index{0};
        for (auto it = queue.begin(); it != queue.end();)
        {
            int height{(*it)[0]};
            int frontTaller{(*it)[1]};
            
            if (index <= frontTaller)
            {
                it++;
                index++;
                continue;
            }
            
            vector<int> temp{*it};
            int tempIndex{0};

            for(auto it2 = queue.begin(); it2 != it; it2++)
            {
                if (tempIndex == frontTaller)
                {
                    queue.insert(it2, temp);
                    it2 = it++;
                    queue.erase(it2);
                    break;
                }

                if (height <= (*it2)[0])
                {
                    tempIndex++;
                }
            }

            index++;
        }

        vector<vector<int>> result(queue.begin(), queue.end());
            
        return result;
    }
};

0개의 댓글