[LeetCode] 1282. Group the People Given the Group Size They Belong To
Updated:
Group the People Given the Group Size They Belong To
μμ΄ ν΄μνλκ² λ νλ€μλ€.. μμ΄ κ³΅λΆ μ’ μ΄μ¬ν ν΄μΌκ² λ€.. κ·Έλλ ν΄μμ΄ μ μλλ©΄ λ°μ μμλ₯Ό λ³΄κ³ μ΄ν΄νλ©΄ λλ€..
groupSizes μ μλ μ«μ ν¬κΈ°λ§νΌ κ·Έλ£Ήμ λ§λ€ μ μκ³ κ·Έ κ·Έλ£Ήμ μ«μμ index λ‘ μ΄λ£¨μ΄μ§λ€.
[3, 3, 3, 3, 3, 1, 3] μ ν¬κΈ°κ° 3 μΈ κ·Έλ£Ή λ κ°, ν¬κΈ°κ° 1 μΈ κ·Έλ£Ή ν κ°λ₯Ό λ§λ€ μ μλ€.
λ¬Έμ μ λ§μ§λ§μ 보면 μ λ΅μ κ²½μ° μ€ λ§λ κ² ν κ°λ§ λ°ννλΌκ³ νλ€.
class Solution:
def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
output = []
for i in groupSizes:
if i == -1:
continue
tmp = []
for j in range(i):
tmp.append(groupSizes.index(i))
groupSizes[groupSizes.index(i)] = -1
output.append(tmp)
return output
μ²μμ λ± μκ°λλ λλ‘ νμ΄λ³΄λ μ λ΅μ λ§μμ§λ§ μλμμ νμ 5%κ° λμλ²λ Έλ€.. 2μ€ ν¬λ¬Έμ΄ μμΌλ κ·Έλ΄λ§ νλ€ !!!
νμ§λ§ λμ ν λ€λ₯Έ λ°©λ²μ΄ μκ°μ΄ μλ κ²μμ ν΄λ³΄λ hash λ₯Ό μ¬μ©νλ©΄ λ λ°° κ°λ 빨리 ν μ μμλ€.
class Solution:
def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
output = []
idx_dict = collections.defaultdict(list)
for idx, i in enumerate(groupSizes):
idx_dict[i].append(idx)
for key in idx_dict:
for i in range(0, len(idx_dict[key]), key):
output.append(idx_dict[key][i:i + key])
return output
λ§μ½ key κ° 2μΈλ° value μ κΈΈμ΄κ° 2κ° λλλ€λ©΄ value λ₯Ό 2μ© λλμ΄ μ€μΌ νλ€.
μ΄κ±Έ μ΄λ»κ² ꡬν ν κΉ κ³ λ―Όμ΄μλλ° range λ μ«μλ₯Ό μΌλ§μ© μ¦κ°μν¬μ§ μ ν΄μ€ μ λ μλ€..
Leave a comment