1282. Group the People Given the Group Size They Belong To**

1282. Group the People Given the Group Size They Belong To**

https://leetcode.com/problems/group-the-people-given-the-group-size-they-belong-to/

題目描述

There are n people whose IDs go from 0 to n - 1 and each person belongs exactly to one group. Given the array groupSizes of length n telling the group size each person belongs to, return the groups there are and the people’s IDs each group includes.

You can return any solution in any order and the same applies for IDs. Also, it is guaranteed that there exists at least one solution.

Example 1:

Input: groupSizes = [3,3,3,3,3,1,3]
Output: [[5],[0,1,2],[3,4,6]]
Explanation: 
Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].

Example 2:

Input: groupSizes = [2,1,3,3,3,2]
Output: [[1],[0,5],[2,3,4]]

Constraints:

  • groupSizes.length == n
  • 1 <= n <= 500
  • 1 <= groupSizes[i] <= n

C++ 實現 1

題目大意是說, 每個人都有 1 個 ID, 給定了大小爲 n 的數組 groupSizes, 表示每個人的 ID 屬於的那個 Group 的大小, 比方說 groupSizes[0] == 3, 說明第 0 個人他所屬的那個組大小爲 3; 現在題目的要求相當於, 我們給出一種 Group 的劃分方式, 使得每個組的大小和 groupSizes 的一致.

具體思路是, 使用哈希表統計擁有相同 group size 的有哪些人, 然後對這些人進行合理的分配.

class Solution {
public:
    vector<vector<int>> groupThePeople(vector<int>& groupSizes) {
        unordered_map<int, vector<int>> group;
        vector<vector<int>> res;
        // 統計擁有相同 group size 的人有哪些
        for (int i = 0; i < groupSizes.size(); ++ i) group[groupSizes[i]].push_back(i);
        for (auto &p : group) {
            auto gs = p.first;
            auto index = p.second;
            // 對於擁有相同 group size (gs) 的這些人, 他們的個數肯定是 gs 的整數倍
            // 那麼我們就知道可以將這些人劃分爲 index.size() / gs 個 Group 了.
            for (int i = 0; i < index.size() / gs; ++ i) {
                vector<int> tmp;
                std::copy(index.begin() + i * gs, index.begin() + (i + 1) * gs, back_inserter(tmp));
                res.push_back(tmp);
            }
        }
        return res;
    }
};

C++ 實現 2

來自 LeetCode 的 Submission.

class Solution {
public:
    vector<vector<int>> groupThePeople(vector<int>& groupSizes) {
        vector<vector<int>> m(groupSizes.size()+1);
        vector<vector<int>> groups;
        groups.reserve(groupSizes.size());
        
        for (int i = 0; i < groupSizes.size(); i++) {
            m[groupSizes[i]].push_back(i);
            if (m[groupSizes[i]].size() == groupSizes[i]) {
                groups.push_back(m[groupSizes[i]]);
                m[groupSizes[i]].clear();
            }
        }
        return groups;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章