Java 101 Chapter 5

Jesus PF
Oct 18, 2020

--

The following question comes from letcode:

1282. Group the People Given the Group Size They Belong To

There are n people that are split into some unknown number of groups. Each person is labeled with a unique ID from 0 to n - 1.

You are given an integer array groupSizes, where groupSizes[i] is the size of the group that person i is in. For example, if groupSizes[1] = 3, then person 1 must be in a group of size 3.

Return a list of groups such that each person i is in a group of size groupSizes[i].

Each person should appear in exactly one group, and every person must be in a group. If there are multiple answers, return any of them. It is guaranteed that there will be at least one valid solution for the given input.

My solution is below:

I create a hashmap saving how many people belong to each party number, when I find the party meets the number of members, I consider the group to be complete, and add it to the final result;

class Solution {
public List<List<Integer>> groupThePeople(int[] groupSizes) {
List<List<Integer>> result= new ArrayList<List<Integer>>();
HashMap<Integer, List<Integer>> map=new HashMap<Integer, List<Integer>>();
for(int i=0; i<groupSizes.length;i++){
if(map.containsKey(groupSizes[i]) ){
List<Integer> list=map.get(groupSizes[i]);
list.add(i);
if(list.size() == groupSizes[i]){
result.add(list);
map.put( groupSizes[i], new ArrayList<Integer>() );
}
}else{
List<Integer> list=new ArrayList<Integer>();
list.add(i);
map.put(groupSizes[i], list );
if(list.size() == groupSizes[i]){
result.add(list);
map.put(groupSizes[i], new ArrayList<Integer>() );
}
}
}return result;

}
}

--

--

Jesus PF
Jesus PF

Written by Jesus PF

I am en electronics engineer, graduated from ITESM. Experienced working as functional validation and software development.

No responses yet