题目
题目链接:https://leetcode-cn.com/problems/group-the-people-given-the-group-size-they-belong-to/
题目解析:
- 创建map集合,用于存放分组的list集合
- 循环开始,当分组的索引在map集合中如果没有,就创建一个放进去
- 如果在map集合有,则将当前的值放入map对应的索引的list集合中
代码
class Solution {
public List<List<Integer>> groupThePeople(int[] groupSizes) {
//创建答案集合
List<List<Integer>> lists = new ArrayList<List<Integer>>();
//创建map集合来存放索引
Map<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>();
//循环遍历
for(int i=0;i<groupSizes.length;i++) {
//如果当前分组的值在map中没有就创建一个
if(!map.containsKey(groupSizes[i])) {
map.put(groupSizes[i], new ArrayList<>());
}
//创建list集合来存相同索引的值
List<Integer> list = map.get(groupSizes[i]);
list.add(i);
//将list集合放回map集合中
map.put(groupSizes[i], list);
//如果当前list集合满足条件,则放入答案集合中。
if(list.size()==groupSizes[i]) {
lists.add(new ArrayList<Integer>(list));
list.clear();
}
}
return lists;
}
}