[프로그래머스] 최빈값 구하기

janjanee·2023년 8월 13일
0

코딩테스트

목록 보기
1/6

[프로그래머스] 최빈값 구하기

내 풀이

def solution(array):
    if len(array) == 1: # early return 
        return array[0]

    element_count = {}

    for element in array:
        element_count[element] = element_count.get(element, 0) + 1 # dict에 해당 값을 key로 해서 +1씩 해준다.

    sorted_elements = sorted(element_count.items(), key=lambda item: item[1], reverse=True) # value를 기준으로 내림차순 정렬

    if len(sorted_elements) > 1 and sorted_elements[0][1] == sorted_elements[1][1]: # 가장 첫번째 value와 두번째 value가 같으면 -1 return 
        return -1

    return sorted_elements[0][0] # 첫번째 요소 value return

다른 사람 풀이

def solution(array):
    while len(array) != 0:
        for i, a in enumerate(set(array)):
            array.remove(a)
        if i == 0: return a
    return -1

참신한 코드!

from collections import Counter

def solution(array):
    a = Counter(array).most_common(2)
    if len(a) == 1:
        return a[0][0]
    if a[0][1] == a[1][1]:
        return -1
    return a[0][0]

Counter 클래스를 이용해서 빈도수가 가장 높은 두 개의 요소와 빈도수를 구한다.
python Counter 클래스를 사용해본적이 없는데 꽤 유용해보인다.

def solution(array):
    answer = 0
    idx = [0] * 1001
    for i in array:
        idx[i] +=1
    if idx.count(max(idx)) >1:
        return -1
    return idx.index(max(idx))

처음에 이런 방식으로 풀어보려다가 바로 적용이 안돼서 dict와 sort를 사용했었는데
이 방법도 깔끔해 보인다.

profile
얍얍 개발 펀치

1개의 댓글

comment-user-thumbnail
2023년 8월 13일

많은 도움이 되었습니다, 감사합니다.

답글 달기