무냐의 개발일지
Heap: Kth Smallest Element in an Array (파이썬 remove(), pop(), del 의 차이점) 본문
Heap: Kth Smallest Element in an Array (파이썬 remove(), pop(), del 의 차이점)
무냐코드 2024. 7. 3. 11:37
1. remove(value)
remove()는 리스트에서 첫 번째로 등장하는 특정 값을 제거합니다. 해당 값이 리스트에 없으면 ValueError가 발생합니다.
# 예시 리스트
fruits = ['apple', 'banana', 'cherry', 'banana']
# 'banana' 제거
fruits.remove('banana')
print(fruits) # ['apple', 'cherry', 'banana']
2. pop(index)
pop()는 리스트에서 지정한 인덱스의 요소를 제거하고, 그 요소를 반환합니다. 인덱스를 지정하지 않으면 마지막 요소를 제거하고 반환합니다. 인덱스가 리스트 범위를 벗어나면 IndexError가 발생합니다
# 예시 리스트
fruits = ['apple', 'banana', 'cherry']
# 인덱스 1의 요소 제거 및 반환
removed_fruit = fruits.pop(1)
print(removed_fruit) # 'banana'
print(fruits) # ['apple', 'cherry']
# 인덱스를 지정하지 않으면 마지막 요소 제거 및 반환
removed_fruit = fruits.pop()
print(removed_fruit) # 'cherry'
print(fruits) # ['apple']
3. del
del은 리스트의 특정 인덱스에 있는 요소를 제거하거나, 슬라이싱을 통해 여러 요소를 제거할 수 있습니다. 또한 리스트 전체를 삭제할 수도 있습니다.
# 예시 리스트
fruits = ['apple', 'banana', 'cherry', 'date']
# 인덱스 1의 요소 제거
del fruits[1]
print(fruits) # ['apple', 'cherry', 'date']
# 슬라이싱을 통해 여러 요소 제거
del fruits[1:3]
print(fruits) # ['apple']
# 리스트 전체 삭제
del fruits
# fruits는 더 이상 존재하지 않음
# print(fruits) # NameError 발생
👩💻 문제
You are given a list of numbers called nums and a number k.
Your task is to write a function find_kth_smallest(nums, k) to find the kth smallest number in the list.
The list can contain duplicate numbers and k is guaranteed to be within the range of the length of the list.
This function will take the following parameters:
nums: A list of integers
k: An integer.
This function should return the kth smallest number in nums.
💡 풀이
def find_kth_smallest(nums, k):
max_heap = MaxHeap()
for i in nums:
max_heap.insert(i)
if len(max_heap.heap) > k:
max_heap.remove()
return max_heap.remove()
우리는 kth smallest 값만 알면 되니까, 굳이 heap을 멀쩡히 유지할 필요가 없다
max heap을 만들고 뒤에서부터 하나씩 제거하면 되는거다
✍️ 해설
왜 pop() 대신 remove()를 사용해야 하는가?
힙 구조 유지: pop() 메서드는 내장 리스트의 마지막 요소를 제거합니다. 이는 힙의 성질을 깨뜨릴 수 있습니다.
반면, remove() 메서드는 heapq 모듈을 사용하여 힙의 최댓값(최소 힙의 경우 최솟값)을 제거하면서 힙 구조를 유지합니다.
최대 힙의 적절한 제거: MaxHeap 클래스에서 remove() 메서드는 최대 힙에서 최대값을 적절히 제거하고 힙 구조를 재정렬합니다. pop() 메서드는 이런 기능이 없으므로 최대 힙을 구현할 때 적합하지 않습니다.
따라서 pop() 대신 remove()를 사용해야 올바르게 최대 힙의 최대값을 제거하고 힙의 성질을 유지할 수 있습니다.
🥳 배운점
remove 와 pop의 차이점! heap에서는 구조를 유지하기 위해 remove를 쓸 것
근데!! 여기서 remove는 무조건 맨 앞에거를 삭제하는 함수잖아
그러니까 그걸로 하나씩 쳐나가는거지. 파이썬 기본 내장 함수랑 관련 x
'LeetCode 코딩테스트' 카테고리의 다른 글
88. Merge Sorted Array (좀 걸림) (0) | 2024.07.03 |
---|---|
Heap: Maximum Element in a Stream (1) | 2024.07.03 |
[기본개념] Heap 구조 (1) | 2024.07.03 |
[기본개념] Graph 구조 (0) | 2024.07.01 |
HT: Subarray Sum * (0) | 2024.07.01 |