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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值