Leetcode 1282 - Group the People Given the Group Size They Belong To

題目

Problem#

有 $n$ 個人要分組,給你一個整數陣列 groupSizes,其中 groupSizes[i] 代表第 $i$ 個人要待在大小 groupSizes[i] 的組別,要你回傳最後分組的情況。
限制:每個人只會在一個組內,如果有多組解,輸出一種即可,測資保證一定至少有一組解。

測資限制#

  • $1 \le n \le 500$
  • $1 \le \text{groupSzie[i]} \le n$

想法#

統計想要被分到組大小 j 的所有人到一個陣列 arr[j] 裡頭,全部掃過一次之後,直接根據組大小去產生 answer 陣列

  • 時間複雜度: $\mathcal{O}(n)$
    • 每個元素只會被推進 ans 一次,總共 n 個元素
  • 空間複雜度: $\mathcal{O}(n)$

AC Code#