Group the People Given the Group Size They Belong To
给一个数组, 每个数表示该位上的group的大小. 求组成这种数组的一个可能.
这个题就是用map存一下<大小, List<位>>, 然后每次先看map里有没有已经建立的数组, 如果没有就建一个把当前位置放进去, 如果有, 就看大小是不是满足当前的数, 如果满足就加到结果里, 如果不满足就放当前的位进去.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Solution { public List<List<Integer>> groupThePeople(int[] groupSizes) { List<List<Integer>> res = new ArrayList<>(); int n = groupSizes.length; HashMap<Integer, List<Integer>> map = new HashMap<>(); for(int i = 0 ; i < groupSizes.length; i++) { int size = groupSizes[i]; List<Integer> tmp = map.getOrDefault(size, new ArrayList<>()); tmp.add(i); map.put(size, tmp); if(tmp.size() == size) { res.add(tmp); map.remove(size); } } return res; } } |