View

문제

숫자로 이루어진 배열인 nums를 인자로 전달합니다.

숫자중에서 과반수(majority, more than a half)가 넘은 숫자를 반환해주세요.

예를 들어,

nums = [3,2,3]
return 3
 
nums = [2,2,1,1,1,2,2]
return 2

 

가정

nums 배열의 길이는 무조건 2 이상입니다.


 

나의 풀이

def more_than_half(nums):
    
    index_dict = {}
    for i in range(0,len(nums)):
        count = 0
        for j in range(0,len(nums)):
            if nums[i] == nums[j]:
                count+=1
        ind = nums[i]        
        index_dict[ind] = count

    for k in nums:
        if index_dict[k] >= (len(nums)//2):
            return k

구현시 알게된 것

1. dictionary에 값을 저장할 때 append로 저장하였더니, 오류가 났다. append는 list를 저장할 때 쓰도록 하자!

2. 반복문 사용시 처음에 for i in len(nums)라고 하였더니, 반복문이 error가 났다. 
     for i in range(0,len(nums))로 수정하였더니 해결!


짝의 풀이

def more_than_half(nums):
    count = {}
    for number in nums:
        try: count[number] += 1
        except: count[number] = 1
    count_list = sorted(count, key=lambda x : count[x], reverse = True)
    return count_list[0]

구현시 알게된 것

1. 1이라는 key가 또 나오면, 1의 value가 1씩 더해지게 되는 원리.

2. sorted 메소드의 옵션인 lambda함수의 기능

count_list = sorted(count, key=lambda x : count[x], reverse = True)

 

 

 * 참고 : https://engineer-mole.tistory.com/94

Share Link
reply
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31