题目地址(1282. 用户分组)
题目描述
有 n 位用户参加活动,他们的 ID 从 0 到 n - 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
Python3 Code:
class Solution:
def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
from collections import defaultdict
resDict = defaultdict(list)
#根据用户组的数量进行粗分组
for index,val in enumerate(groupSizes):
resDict[val].append(index)
resList = []
#根据key为数量进行细分组,把相同分组的分成多个小
for key,valList in resDict.items():
tempNum = 0
tempList = []
while len(valList)!= 0:
tempNum += 1
tempList.append(valList.pop())
if tempNum % key == 0:
resList.append(tempList)
tempList = []
return resList
if __name__ == '__main__':
groupSizes = [3,3,3,3,3,1,3]
ret = Solution().groupThePeople(groupSizes)
print(ret)
复杂度分析
令 n 为数组长度。
- 时间复杂度:
- 空间复杂度: