1. 程式人生 > >LeetCode 406. Queue Reconstruction by Height (依據高度進行佇列重構)

LeetCode 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.

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

Reference Answer

Method one

這個題怎麼想出來的呢?是因為我們考慮如果先把個子高的排好序,那麼在任何位置插入資料都不會對已經排好序的陣列造成影響。而,與此同時,我們已經知道了個子高的排序,那麼當新的資料到的時候,我們要確定它的位置也很簡單,因為現在的所有資料都比他高,所以只要根據他的第二個數字確定他的位置即可。

先對已有的陣列進行排序。按照高度降序排列,如果高度一樣,按照k的值升序排列。這樣比如一開始[7,0] [7,1] [7,2]就會排好,然後比如說後面有一個[6,1], 說明只有一個大於或等於它,又因為比6大的已經全部取出。所以把它放在位置1,這樣就變成[7,0] [6,1] [7,1] [7,2].然後比如又有一個[5,0].就放在位置0,以此類推。

即對於案列。首先排序成:

[[7,0],[7,1],[6,1],[5,0],[5,2],[4,4]]

然後對於第二個數字進行插入對應位置:

[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

注:這道題思路不難想,難在第一次接觸這種list隊依據兩個因素排序。

Code

class Solution:
    def reconstructQueue(self, people):
        """
        :type people: List[List[int]]
        :rtype: List[List[int]]
        """
        if not people or not people[0]:
            return []
        temp_people = sorted(people, key = lambda people:(-people[0], people[1]))
        res = []
        for man in temp_people:
            res.insert(man[1], man)
        return res
            

C++ Version:

C++程式碼如下,需要注意自定義sort()函式的比較方法。

注意這種自定義sort函式的方式。

class Solution {
public:
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        sort(people.begin(), people.end(), [](const pair<int, int> a, const pair<int, int> b) {
            return (a.first > b.first) || (a.first == b.first && a.second < b.second);
        });

        vector<pair<int, int>> res;
        for (auto p: people){
            res.insert(res.begin()+p.second, p);
        }
        return res;
    }
};

Note

  • 注意Python排序時需要考慮多個因素的方法:people.sort(key = lambda x : (-x[0], x[1]))temp_people = sorted(people, key = lambda people:(-people[0], people[1])),很值得學習!
  • 對於C++版本,由於自帶sort函式不能完成所需操作,需要自定義排序函式:
sort(people.begin(), people.end(), [](const pair<int, int> a, const pair<int, int> b) {
            return (a.first > b.first) || (a.first == b.first && a.second < b.second);
 });

參考文獻

[1] https://blog.csdn.net/fuxuemingzhu/article/details/68486884