Skip to content

Files

Latest commit

8384416 · Dec 24, 2021

History

History
135 lines (105 loc) · 3.69 KB

File metadata and controls

135 lines (105 loc) · 3.69 KB

English Version

题目描述

有 n 位用户参加活动,他们的 ID 从 0n - 1,每位用户都 恰好 属于某一用户组。给你一个长度为 n 的数组 groupSizes,其中包含每位用户所处的用户组的大小,请你返回用户分组情况(存在的用户组以及每个组中用户的 ID)。

你可以任何顺序返回解决方案,ID 的顺序也不受限制。此外,题目给出的数据保证至少存在一种解决方案。

 

示例 1:

输入:groupSizes = [3,3,3,3,3,1,3]
输出:[[5],[0,1,2],[3,4,6]]
解释: 
其他可能的解决方案有 [[2,1,6],[5],[0,4,3]] 和 [[5],[0,6,2],[4,3,1]]。

示例 2:

输入:groupSizes = [2,1,3,3,3,2]
输出:[[1],[0,5],[2,3,4]]

 

提示:

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

解法

Python3

class Solution:
    def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
        mp = defaultdict(list)
        for i, x in enumerate(groupSizes):
            mp[x].append(i)
        res = []
        for x, indexes in mp.items():
            l = len(indexes)
            for i in range(0, l, x):
                res.append(indexes[i: i + x])
        return res

Java

class Solution {
    public List<List<Integer>> groupThePeople(int[] groupSizes) {
        Map<Integer, List<Integer>> mp = new HashMap<>();
        for (int i = 0; i < groupSizes.length; ++i) {
            mp.computeIfAbsent(groupSizes[i], k -> new ArrayList<>()).add(i);
        }
        List<List<Integer>> res = new ArrayList<>();
        for (Map.Entry<Integer, List<Integer>> entry : mp.entrySet()) {
            int x = entry.getKey();
            List<Integer> indexes = entry.getValue();
            for (int i = 0; i < indexes.size(); i += x) {
                res.add(new ArrayList<>(indexes.subList(i, i + x)));
            }
        }
        return res;
    }
}

C++

class Solution {
public:
    vector<vector<int>> groupThePeople(vector<int>& groupSizes) {
        unordered_map<int, vector<int>> mp;
        for (int i = 0; i < groupSizes.size(); ++i) mp[groupSizes[i]].push_back(i);
        vector<vector<int>> res;
        for (auto& entry : mp)
        {
            int x = entry.first;
            auto indexes = entry.second;
            for (int i = 0; i < indexes.size(); i += x)
            {
                vector<int> t(indexes.begin() + i, indexes.begin() + i + x);
                res.push_back(t);
            }
        }
        return res;
    }
};

Go

func groupThePeople(groupSizes []int) [][]int {
	mp := make(map[int][]int)
	for i, x := range groupSizes {
		mp[x] = append(mp[x], i)
	}
	var res [][]int
	for x, indexes := range mp {
		for i := 0; i < len(indexes); i += x {
			res = append(res, indexes[i:i+x])
		}
	}
	return res
}

...