[프로그래머스][LV.0] 최빈값 구하기 | python3
2025. 2. 10. 11:59ㆍ프로그래머스/LV.0
문제 링크: 최빈값 구하기
문제 설명
문제 설명
빈값은 주어진 값 중에서 가장 자주 나오는 값을 의미합니다. 정수 배열 array가 매개변수로 주어질 때, 최빈값을return 하도록 solution 함수를 완성해보세요. 최빈값이 여러 개면 -1을 return 합니다
제한사항
0 < array의 길이 < 100
0 ≤ array의 원소 < 1000
문제 풀이
딕셔너리로 해당 숫자가 몇번 나왔는지 기록하고 빼냄.
리스트로 바꾸어서 count하는데서 시간복잡도가 올라갈 것 같음
내코드
def solution(array):
dict={}
for i in array:
if i not in dict:
dict[i]=1
else:
dict[i]+=1
max_freq=max(dict.values())
most_frequent=[key for key, value in dict.items() if value == max_freq ]
return most_frequent[0] if len(most_frequent)==1 else -1
#다시풀어봄
def solution(array):
n_dict={}
for a in array:
if a not in n_dict.keys():
n_dict[a]=1
else:
n_dict[a]+=1
maxvalue=0
for key,value in n_dict.items():
maxvalue=max(maxvalue,value)
if maxvalue==value:
result=key
if list(n_dict.values()).count(n_dict[result])>1:
return -1
return result
더보기
다른사람풀이
def solution(array):
dict={}
for i in array:
if i not in dict:
dict[i]=1
else:
dict[i]+=1
modenum=0
for key in dict:
if dict[key]>modenum:
modenum=dict[key]
elif dict[key]==modenum:
modenum=-1
return modenum
def solution(array):
dict={}
for i in array:
if i not in dict:
dict[i]=1
else:
dict[i]+=1
modenum=0
for key in dict:
if dict[key]>modenum:
modenum=dict[key]
if dict.values().count(modenum)!=1:
modenum=-1
꼭 리스트로 안바꾸어줘도 count 사용 가능하군
def solution(array):
dict={}
for i in array:
if i not in dict:
dict[i]=1
else:
dict[i]+=1
max_freq=max(dict.values())
most_frequent=[key for key, value in dict.items() if value == max_freq ]
return most_frequent[0] if len(most_frequent)==1 else -1
'프로그래머스 > LV.0' 카테고리의 다른 글
[프로그래머스][LV.0] 저주의 숫자 3 | python3 (0) | 2025.02.10 |
---|---|
[프로그래머스][LV.0] 유한소수 판별하기 | python3 (0) | 2025.02.10 |
[프로그래머스][LV.0] 문자열 여러 번 뒤집기 | python3 (0) | 2025.02.03 |
[프로그래머스][LV.0] 주사위 게임 3 | python3 (0) | 2025.02.03 |
[프로그래머스][LV.0] 배열 만들기 2 | python3 (0) | 2025.02.03 |