무냐의 개발일지

HT: Find Duplicates 본문

LeetCode 코딩테스트

HT: Find Duplicates

무냐코드 2024. 6. 19. 15:48

 

| GET (key 값에 해당하는 value를 반환한다)

 

1. 'apple' 키에 해당하는 값을 반환합니다.

2. 'orange' 키가 존재하지 않기 때문에 None을 반환합니다.

3. 'orange' 키가 존재하지 않지만, 기본값으로 'N/A'를 지정해주었기 때문에 'N/A'를 반환합니다.

get('key', 0) : key에 해당하는 value를 반환하지만, 그 딕셔너리에 해당 키가 존재하지 않는다면 0으로 지정한다

value = my_dict.get('apple')
print(value)  # 출력: 1

value = my_dict.get('orange')
print(value)  # 출력: None

value = my_dict.get('orange', 'N/A')
print(value)  # 출력: N/A

 

 

| ITEMS 

  • key와 value를 한꺼번에 for문을 반복하려면 items() 를 사용합니다.
>>> for key, val in a.items():
...     print("key = {key}, value={value}".format(key=key,value=val))
... 
key = alice, value=[1, 2, 3]
key = bob, value=20
key = tony, value=15
key = suzy, value=30

 

참고) 리스트에서 인덱스와 값을 반복할 때는 enumerate() !!

 

| IN

  • dictionary의 in은 키에 한해서 동작합니다.
>>> 'alice' in a
True
>>> 'teacher' in a
False
>>> 'teacher' not in a
True


if sorted_string in anagrams: #딕셔너리에 sorted_string이라는 키가 있을 때
   anagrams[sorted_string].append(string)

 

 

| SORTED

string = "eat"

sorted(string)
>> ['a', 'e', 't']

''.join(sorted(string))
>> 'aet'

 

알파벳 순서로 sorted 처리하면, 리스트로 나온다. 얘를 다시 String으로 만드려면 ''.join 을 해줘야 함

* 디폴트가 reverse = False이고, 오름차순 (1,2,3,4,....) 으로 정렬되므로, 내림차순 하고 싶으면 sorted 괄호 안에 reverse =True를 해준다

 

sorted([100, 4, 200, 1, 3, 2])
>> [1, 2, 3, 4, 100, 200]

sorted([100, 4, 200, 1, 3, 2], reverse= True)
>> [200, 100, 4, 3, 2, 1]

 


 

👩‍💻 문제

Problem: Given an array of integers nums, find all the duplicates in the array using a hash table (dictionary).

중복되는 애만 리스트로 출력하는 함수


Input:

  • A list of integers nums.


Output:

  • A list of integers representing the numbers in the input array nums that appear more than once. If no duplicates are found in the input array, return an empty list [].

 

 

💡 풀이

1) 내 해답
def find_duplicates(nums):
    my_dict = {}
    result = []
    for i in nums:
        if i not in my_dict:
            my_dict[i] = True
        else:
            result.append(i)
    return result
    
   
2) 답지 해답
def find_duplicates(nums):
    num_counts = {}
    for num in nums:
        num_counts[num] = num_counts.get(num, 0) + 1
 
    duplicates = []
    for num, count in num_counts.items():
        if count > 1:
            duplicates.append(num)
 
    return duplicates

 

 

✍️ 해설

 

나는 일단 냅다 딕셔너리 만들어서, 그 안에 없는 값들은 다 넣어두고,

혹시 쌓는 와중에 그 값이 발견됐다 싶으면, 바로 duplicated 리스트에 넣어서, 그 리스트를 반환한다

 

해답은 딕셔너리를 만들지만, 키값이 몇 번 나왔는지 그 횟수도 저장하느라 get을 쓴다

다 넣은 다음에 해당 딕셔너리에서 value의 등장 갯수가 1번을 초과했을 때, 답지에 추가해서 리턴한다

몇 번 나왔는지 횟수를 트래킹 할 때는 더 좋은 방법같다.

 

🥳 배운점

get, items method 사용법

'LeetCode 코딩테스트' 카테고리의 다른 글

BST: Convert Sorted List to Balanced BST  (0) 2024.07.01
BST: Invert Binary Tree  (0) 2024.07.01
DLL: Swap Nodes in Pairs (Advanced!)  (0) 2024.06.18
Stack : sort_stack 해설  (0) 2024.06.17
LL: Reverse Between 해설  (0) 2024.06.14