作者Rushia (みけねこ的鼻屎)
看板Marginalman
標題Re: [閒聊] 每日LeetCode
時間Mon Sep 11 17:35:41 2023
https://leetcode.com/problems/group-the-people-given-the-group-size-they-belong-to/description/
1282. Group the People Given the Group Size They Belong To
給你一個 size 為 n 的陣列 groupSizes 表示編號 0 ~ n-1 的人,groupSizes[i] 表
示編號為 i 的人在的組別有幾個人,返回一個列表,這個列表表示了 n 個人被分成對
應人數的組別,題目保證至少有一解,組別順序隨意。
Example 1:
Input: groupSizes = [3,3,3,3,3,1,3]
Output: [[5],[0,1,2],[3,4,6]]
Explanation:
The first group is [5]. The size is 1, and groupSizes[5] = 1.
The second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1]
= groupSizes[2] = 3.
The third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4]
= groupSizes[6] = 3.
Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].
Example 2:
Input: groupSizes = [2,1,3,3,3,2]
Output: [[1],[0,5],[2,3,4]]
思路:
1.利用一個 map 紀錄 key = 這個組的目標人數 value = 這個組的成員。
2.每次都往目標人數的列表添加成員,當滿足人數的時候表示分組完畢,將map清空,
並把組的成員加入結果集。
Java Code:
-------------------------------------------
class Solution {
public List<List<Integer>> groupThePeople(int[] groupSizes) {
List<List<Integer>> res = new ArrayList<>();
Map<Integer, List<Integer>> map = new HashMap<>();
for (int i = 0; i < groupSizes.length; i++) {
if (!map.containsKey(groupSizes[i])) {
map.put(groupSizes[i], new ArrayList<>());
}
List<Integer> curr = map.get(groupSizes[i]);
curr.add(i);
if (curr.size() == groupSizes[i]) {
res.add(new ArrayList<>(curr));
map.remove(groupSizes[i]);
}
}
return res;
}
}
-------------------------------------------
--
https://i.imgur.com/YPBHGGE.jpg
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.73.13 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1694424944.A.967.html
推 sustainer123: 大師 09/11 17:45
推 JerryChungYC: 數字由小到大 再根據數字大小依序放進去嗎 09/11 18:34
不用照大小 數字只是表示編號
※ 編輯: Rushia (122.100.73.13 臺灣), 09/11/2023 20:39:13