프로그래머스/LV2
[프로그래머스 Lv2,python]- 귤 고르기
chyam_eun
2024. 12. 29. 18:06
def solution(k, tan):
dic={}
tan_set=set(tan) #집합으로 저장하기
li=[] # 딕셔너리의 값을 저장할곳
cnt=0 #개수 저장
for a in tan_set: #딕셔너리에 값 추가
dic[a]=0
for a in tan: #개수 추가
dic[a]+=1
for key,value in dic.items():
li.append(value) # 개수를 리스트로 저장
li.sort(reverse=True) # 내림차순
while(k>0):
k-=li[cnt]
cnt+=1
return cnt
counter을 사용하지않고 구현했음. 아래는 counter을 사용한 풀이임.
counter을 사용하면 딕셔너리 형태로 개수를 {1:2, 2:1 } 이런식으로 횟수를 알수있다.
def solution(k, tan):
from collections import Counter
counts = Counter(tan)
# 등장 횟수를 내림차순으로 정렬
sorted_counts = sorted(counts.values(), reverse=True)
# 최소한의 요소 개수를 선택
cnt = 0
for count in sorted_counts:
k -= count
cnt += 1
if k <= 0: # k가 0 이하로 떨어지면 종료
break
return cnt