본문 바로가기
알고리즘/TIL

[99클럽 코테 스터디 28일차 TIL] 배열

by 모모_모 2024. 6. 17.

✏️  오늘의 문제 : 1282. Group the People Given the Group Size They Belong To

📌 주안점

  • i번째 사람이 속해있는 그룹의 groupsize가 주어진다.
    • 모든 사람이 그룹을 이루는 경우임이 보장된다.
    • groupsize가 같은 i끼리 모이도록 하자.
  • index가 사람이 아닌, groupsize가 되도록 
    • groupsize[1] = [ [1],[2],[3] ]
    • groupsize[4] = [ [4,5,6,7], [8,9,10,11] ]

 

📌 해결 방법

 

  • Dictionary groupDict를 만들어, key를 size로 value를 참가자 리스트의 형태로 변환한다.
  • key의 크기로 value list를 분할한다. 그 리스트의 값을 ans에 담아 리턴한다.
class Solution(object):
    def groupThePeople(self, groupSizes):
        """
        :type groupSizes: List[int]
        :rtype: List[List[int]]
        """
        groupDict = {}
        ans = []
        for i in range(len(groupSizes)):
            cs = groupSizes[i]
            if cs in groupDict.keys(): groupDict[cs].append(i)
            else: groupDict[cs] = [i]
        print(groupDict)
        
        for k,v in groupDict.items():
            curans = []
            cnt = 0
            for j in v:
                cnt += 1
                curans.append(j)
                if cnt >= k:
                    ans.append(curans)
                    curans = []
                    cnt = 0
        return ans