-
귤 고르기python algorithm 2024. 3. 8. 15:30
[문제 설명]
경화는 과수원에서 귤을 수확했습니다. 경화는 수확한 귤 중 'k'개를 골라 상자 하나에 담아 판매하려고 합니다. 그런데 수확한 귤의 크기가 일정하지 않아 보기에 좋지 않다고 생각한 경화는 귤을 크기별로 분류했을 때 서로 다른 종류의 수를 최소화하고 싶습니다.
예를 들어, 경화가 수확한 귤 8개의 크기가 [1, 3, 2, 5, 4, 5, 2, 3] 이라고 합시다. 경화가 귤 6개를 판매하고 싶다면, 크기가 1, 4인 귤을 제외한 여섯 개의 귤을 상자에 담으면, 귤의 크기의 종류가 2, 3, 5로 총 3가지가 되며 이때가 서로 다른 종류가 최소일 때입니다.
경화가 한 상자에 담으려는 귤의 개수 k와 귤의 크기를 담은 배열 tangerine이 매개변수로 주어집니다. 경화가 귤 k개를 고를 때 크기가 서로 다른 종류의 수의 최솟값을 return 하도록 solution 함수를 작성해주세요.[제한사항]
- 1 ≤ k ≤ tangerine의 길이 ≤ 100,000
- 1 ≤ tangerine의 원소 ≤ 10,000,000
[풀이]
-1. 최초 풀이
def solution(k, tangerine): answer = len(set(tangerine)) tangerine_list = sorted(tangerine.count(item) for item in set(tangerine)) length = len(tangerine) for cnt in tangerine_list: if length - cnt >= k: answer -= 1 length -= cnt else: break return answer
tangerine_list = sorted(tangerine.count(item) for item in set(tangerine))
tangerine_list를 구성하는데, set(tangerine)의 각 요소마다 tangerine 리스트 전체를 읽으며 .count를 하게 되는데, 이 경우 tangerine 리스트의 크기가 매우 크고 종류가 모두 다르다면 정말 많은 연산이 필요하여 시간 초과가 발생. 따라서, tangerine 리스트를 한 번만 읽으면서도 tangerine_list를 구해야하는게 핵심 포인트
-2. 수정 풀이
def solution(k, tangerine): answer = len(set(tangerine)) tangerine_dict = {} length = len(tangerine) for item in tangerine: if item in tangerine_dict: tangerine_dict[item] += 1 else: tangerine_dict[item] = 1 for item, cnt in sorted(tangerine_dict.items(), key=lambda x:x[1]): if length - cnt >= k: answer -= 1 length -= cnt else: break return answer
'python algorithm' 카테고리의 다른 글
달리기 경주 (0) 2024.03.07 N개의 최소공배수 (0) 2024.02.25 최대공약수와 최소공배수 (0) 2024.02.25 카펫 (0) 2024.02.23 멀리 뛰기 (0) 2024.02.23