문제풀이/일일연습문제

[heap*]99클럽 코테 스터디 9일차 TIL + 0506-relative-ranks

Mo_bi!e 2024. 7. 31. 17:55

506. Relative Ranks

Easy


You are given an integer array score of size n, where score[i] is the score of the ith athlete in a competition. All the scores are guaranteed to be unique.

The athletes are placed based on their scores, where the 1st place athlete has the highest score, the 2nd place athlete has the 2nd highest score, and so on. The placement of each athlete determines their rank:

  • The 1st place athlete's rank is "Gold Medal".
  • The 2nd place athlete's rank is "Silver Medal".
  • The 3rd place athlete's rank is "Bronze Medal".
  • For the 4th place to the nth place athlete, their rank is their placement number (i.e., the xth place athlete's rank is "x").

Return an array answer of size n where answer[i] is the rank of the ith athlete.

 

Example 1:

Input: score = [5,4,3,2,1]
Output: ["Gold Medal","Silver Medal","Bronze Medal","4","5"]
Explanation: The placements are [1st, 2nd, 3rd, 4th, 5th].

Example 2:

Input: score = [10,3,8,9,4]
Output: ["Gold Medal","5","Bronze Medal","Silver Medal","4"]
Explanation: The placements are [1st, 5th, 3rd, 2nd, 4th].

 

Constraints:

  • n == score.length
  • 1 <= n <= 104
  • 0 <= score[i] <= 106
  • All the values in score are unique.

 

---

<내코드>

import heapq

class Solution:
    def findRelativeRanks(self, score: List[int]) -> List[str]:

        heap = []
        answer = [""] * len(score)

        for i in range(len(score)):
            heapq.heappush(heap, (-score[i],i))
        
        # i = 0
        # for h in (heap) :
            # poped_tuple = h
        for i in range(len(score)):
            poped_tuple = heapq.heappop(heap)

            if i == 0:
                answer[poped_tuple[1]] = "Gold Medal"
            elif i == 1:
                answer[poped_tuple[1]] = "Silver Medal"
            elif i == 2:
                answer[poped_tuple[1]] = "Bronze Medal"
            else:
                answer[poped_tuple[1]] = str(i + 1)
            # i += 1
            

        return answer

    

        # stroed_score = score
        # score.sort(reverse=True)
        # dic = {}

        # for i in range(len(score)):
        #     if i == 0:
        #         dic[score[i]] = "Gold Medal"
        #     elif i == 1:
        #         dic[score[i]] = "Silver Medal"
        #     elif i == 2:
        #         dic[score[i]] = "Bronze Medal"
        #     else :
        #         dic[score[i]] = str(i + 1)
        

        # return dic

1. 해맨부분

(1) 이 문제가 힙과 어떤 관련이 있는건지?

=> 최대힙으로 선수들의 등수를 매기기 위함임

 

(2) 등수를 매겨도 마지막 정답 리턴은 입력 순서대로 해야하는데 어떻게 해야하는건지?

=> 점수(score)와 리스트 위치(i) 를 튜플로 저장하면 됨

 

(2 - 1) 왜 튜플인가?

=> 데이터 쌍의 효율적 관리를 위함

대안은 리스트(불변성 無) / 클래스(복잡성 有) / 딕셔너리 (heapq 에서 비효율)

결국 튜플은 불변성, 간결성, 효율성으로 이용함

 

(3) heap 에 있는 자료를 어떻게 하면 순회하며 pop 할 수있을까?

=> 기존에 push 했던 방법처럼 for문으로 빼내면 됨

 

(4) 각 인덱스별 리턴하는 문자열을 어떻게 동일하게 넣을지? 

append()를 하기에는 밀려나고, 바로 특정인덱스에 대입하기에는 존재하지않음

=> answer 에 대한 리스트 선언할 때 이미 해당크기 만큼 리스트를 미리 선언함

 

(5) heapify() 를 heappush() 대신에 낫지않을까?

=> 맞음 이렇게 하면 매번 heappush() 하지않아서 좋고, 효율성도 좋음

heapify() 는 한번만 이용이 되고, 시간복잡도는 O(n)

heappush() 는 매번 이용이 되고, 시간복잡도는 O(n log n)

 

heap = [(-s, i) for i, s in enumerate(score)] heapq.heapify(heap)

 

 

 

<모범사례>

import heapq
from typing import List

class Solution:
    def findRelativeRanks(self, score: List[int]) -> List[str]:
        # Step 1: Create a max-heap (by pushing negative scores)
        heap = []
        for i, s in enumerate(score):
            heapq.heappush(heap, (-s, i))
        
        # Step 2: Extract elements from heap and assign ranks
        answer = [""] * len(score)
        for rank in range(len(score)):
            score_value, index = heapq.heappop(heap)
            if rank == 0:
                answer[index] = "Gold Medal"
            elif rank == 1:
                answer[index] = "Silver Medal"
            elif rank == 2:
                answer[index] = "Bronze Medal"
            else:
                answer[index] = str(rank + 1)
        
        return answer

# Example usage
solution = Solution()
scores = [5, 4, 3, 2, 1]
print(solution.findRelativeRanks(scores))

- enumerate()

파이썬의 내장함수임 인덱스와 엘리먼트 동시에 접근가능

 

- answer = [""] * len(score):
answer 이라는 리스트에 대해서 score 크기만큼 미리 선언이 가능

- score_value, index = heapq.heappop(heap):
디스트럭쳐링이 됨