# ์ต๋น๊ฐ ๊ตฌํ๊ธฐ # 120812 # lv0
# ๋ฌธ์
์ต๋น๊ฐ์ ์ฃผ์ด์ง ๊ฐ ์ค์์ ๊ฐ์ฅ ์์ฃผ ๋์ค๋ ๊ฐ์ ์๋ฏธํฉ๋๋ค. ์ ์ ๋ฐฐ์ด array๊ฐ ๋งค๊ฐ๋ณ์๋ก ์ฃผ์ด์ง ๋, ์ต๋น๊ฐ์ return ํ๋๋ก solution ํจ์๋ฅผ ์์ฑํด๋ณด์ธ์. ์ต๋น๊ฐ์ด ์ฌ๋ฌ ๊ฐ๋ฉด -1์ return ํฉ๋๋ค.
0 < array์ ๊ธธ์ด < 100
0 ≤ array์ ์์ < 1000
# ์์
[1, 2, 3, 3, 3, 4]์์ 1์ 1๊ฐ 2๋ 1๊ฐ 3์ 3๊ฐ 4๋ 1๊ฐ๋ก ์ต๋น๊ฐ์ 3์
๋๋ค.
[1, 1, 2, 2]์์ 1์ 2๊ฐ 2๋ 2๊ฐ๋ก ์ต๋น๊ฐ์ด 1, 2์
๋๋ค. ์ต๋น๊ฐ์ด ์ฌ๋ฌ ๊ฐ์ด๋ฏ๋ก -1์ return ํฉ๋๋ค.
[1]์๋ 1๋ง ์์ผ๋ฏ๋ก ์ต๋น๊ฐ์ 1์
๋๋ค.
# ํ์ด
๋ด ํ์ด
def solution(array):
dic = {} # dictionary๋ฅผ ํ์ฉํ ๋ฌธ์ ํ์ด๋ค.
# array ๋ฐฐ์ด ๋ด๋ถ์ ์์ ํ๋ํ๋์ ์ ๊ทผ.
for item in array:
if item in dic: # ๋ง์ฝ ์๋ค๋ฉด ๊ฐฏ์๋ฅผ +1
dic[item] += 1
else: # ์์ผ๋ฉด ์๋ก ์ถ๊ฐ.
dic[item] = 1
max_count = max(dic.values()) # dic ๋ด๋ถ์ key๋ค ์ค value ๊ฐ์ด ๊ฐ์ฅ ํฐ ๊ฐ์ max_count์ ํ ๋น.
max_elements = [key for key, value in dic.items() if value == max_count] # list_comprehension
if len(dic) == 1:
return array[0]
elif len(max_elements) == 1:
return max_elements[0]
else:
return -1
# ๋๋์
dictionary์ max() ์ ํ์ฉํด ๋ฌธ์ ๋ฅผ ํ์ด๋ณด์๋ค.. ๋น๊ต์ ๊ฐ๋จํ ๋ฌธ์ ์์๋ ์๊ฐ์ด ๊ฝค ์์๋์๋?(ํด์ ๋ฐฉ์์ผ๋ก ํ์ด๋ณด๋ ค๊ณ ๋ ธ๋ ฅํ๋ค.) ๋ฌธ์ ๋ค.