LeetCode.M1282
题目:
题目大意:
如图所示。
数据范围:
如图所示
思路:
简单模拟,使用HashMap将每个人归类,然后对每一类根据所在组的大小,拆分成小类。
代码:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Solution {
public List<List<Integer>> groupThePeople(int[] groupSizes) {
List<List<Integer>> lists = new ArrayList<List<Integer>>();
Map<Integer, List<Integer>> allgroup = new HashMap<>();
for (int i = 0; i < groupSizes.length; i ++ ){
List<Integer> a = allgroup.getOrDefault(groupSizes[i], new ArrayList<>());
a.add(i);
allgroup.put(groupSizes[i], a);
}
/*
for (int i = 0; i < groupSizes.length; i++) {
int size = groupSizes[i];
allgroup.putIfAbsent(size, new ArrayList<Integer>());
allgroup.get(size).add(i);
}
*/
for (Map.Entry<Integer, List<Integer>> gro : allgroup.entrySet()){
int groId = gro.getKey();
List<Integer> peoId = gro.getValue();
int len = 0;
while (len < peoId.size()){
List<Integer> smallgro = new ArrayList<>();
int cnt = 0;
while (cnt < groId){
smallgro.add(peoId.get(len));
len ++ ;
cnt ++ ;
}
lists.add(smallgro);
}
}
return lists;
}
}
public class Main {
public static void main(String[] args) {
int[] groupSizes = new int[]{3,3,3,3,3,1,3};
Solution solution = new Solution();
System.out.println(solution.groupThePeople(groupSizes));
}
}
时空复杂度分析等:
-
时间复杂度 : O(n)
-
空间复杂度 : O(n)