Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- python sorted
- 릿코드
- 알고리즘풀이
- binary search
- leetcode 풀기
- 파이썬 알고리즘
- 파이썬알고리즘
- 상가수익률계산기
- leetcode풀이
- python priority queue
- 코틀린기초
- LeetCode
- 파이썬릿코드풀기
- 파이썬 프로그래머스
- 파이썬 알고리즘 풀기
- python 릿코드
- 파이썬 릿코드
- 릿코드풀이
- leetcode풀기
- 릿코드 풀기
- python 알고리즘
- 잇츠디모
- 알고리즘풀기
- python zip_longest
- 릿코드풀기
- 파이썬알고리즘풀기
- 파이썬릿코드
- python xor
- 릿코드 파이썬
- python Leetcode
Archives
- Today
- Total
소프트웨어에 대한 모든 것
LeetCode 풀기 - 895. Maximum Frequency Stack 본문
반응형
895. Maximum Frequency Stack
https://leetcode.com/problems/maximum-frequency-stack/
Maximum Frequency Stack - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제)
솔루션1) 시간 초과 발생
시간 초과가 발생합니다.
pop()을 수행할 때마다 sorted()로 정렬을 수행하기 때문에 너무 느립니다.
push() 수행할 때 이미 정렬을 수행해 놓고 pop()에서는 O(1)으로 가져오는 방식으로 최적화가 필요합니다.
from collections import defaultdict
class FreqStack:
def __init__(self):
self.stack = []
self.counter = defaultdict(int)
def push(self, val):
self.stack.append(val)
self.counter[val] += 1
def pop(self):
sorted_counter = sorted(self.counter.items(), key=lambda x: x[1], reverse=True)
most_freq = sorted_counter[0][1]
most_freq_vals = [x[0] for x in list(filter(lambda x: x[1] == most_freq, sorted_counter))]
for i in range(len(self.stack)-1, -1, -1):
if self.stack[i] in most_freq_vals:
self.counter[self.stack[i]] -= 1
ret = self.stack.pop(i)
break
return ret
솔루션2) heapq 사용
heapq를 사용해서 push()가 호출될 때마다 heapq에 push를 수행합니다.
frequency가 크고 최근에 추가된 것으로 정렬되도록 우선수위를 조정합니다.
import heapq as hq
from collections import defaultdict
class FreqStack:
def __init__(self):
self.freq = defaultdict(int)
self.counter = 0
self.heap = []
def push(self, val):
self.freq[val] += 1
# frequency가 크고 나중에 추가될 수록 우선순위가 높음
hq.heappush(self.heap, (-self.freq[val], -self.counter, val))
self.counter += 1
def pop(self):
val = hq.heappop(self.heap)[2]
self.freq[val] -= 1
return val
반응형
'알고리즘 > LeetCode' 카테고리의 다른 글
LeetCode 풀기 - 328. Odd Even Linked List (0) | 2022.03.26 |
---|---|
LeetCode 풀기 - 146. LRU Cache (0) | 2022.03.26 |
LeetCode 풀기 - 71. Simplify Path (0) | 2022.03.15 |
LeetCode 풀기 - 2. Add Two Numbers (0) | 2022.03.11 |
LeetCode 풀기 - 2120. Execution of All Suffix Instructions Staying in a Grid (0) | 2022.03.10 |
Comments