시간 기반 키 값 저장소
'시간 기반 키 값 저장소' 문제에 대한 자세한 가이드 및 Python 구현입니다.
1. 배우다
'시간 기반 키 값 저장소' 문제는 이진 검색 섹션의 주요 과제입니다.
이 구현은 Python의 쉬운 수준 논리에 중점을 둡니다.
우리는 제공되는 솔루션에서 기술적 정확성과 코드 가독성을 최우선으로 생각합니다.
2. Real-World Applications
3. Visual Intuition
시간 기반 키 값 저장소의 논리 흐름을 시각화합니다.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
시간 기반 키 값 저장소에 대한 문제 설명을 주의 깊게 읽어보세요.
2. Formulate brute force
간단한 반복 솔루션 초안을 작성합니다.
3. Identify inefficiency
중복 계산을 찾으십시오.
4. Optimize search path
해싱이나 정렬을 사용하여 프로세스 속도를 높입니다.
5. Final Implementation
생산 표준에 맞게 코드를 정리합니다.
문제 설명
서로 다른 타임스탬프에서 동일한 키에 대한 여러 값을 저장하고 특정 타임스탬프에서 키 값을 검색할 수 있는 시간 기반 키-값 데이터 구조를 설계합니다.
TimeMap 클래스를 구현합니다.
- TimeMap() 객체를 초기화합니다.
- set(key: str, value: str, timestamp: int) 주어진 시간 timestamp에 value 값으로 key 키를 저장합니다.
- get(key: str, timestamp: int) -> str timestamp_prev <= timestamp을 사용하여 이전에 set이 호출된 것과 같은 값을 반환합니다. 이러한 값이 여러 개인 경우 가장 큰 timestamp_prev과 관련된 값을 반환합니다. 값이 없으면 ""을 반환합니다.
- •1 <= key.length, value.length <= 100
- •key and value consist of lowercase English letters and digits
- •1 <= timestamp <= 10^7
- •All timestamps of set are strictly increasing for each key
- •At most 2 * 10^5 calls will be made to set and get
예
["TimeMap", "set", "get", "get", "set", "get", "get"] [[], ["foo", "bar", 1], ["foo", 1], ["foo", 3], ["foo", "bar2", 4], ["foo", 4], ["foo", 5]]
[None, None, "bar", "bar", None, "bar2", "bar2"]
set("foo", "bar", 1): stores bar at time 1. get("foo", 1): returns "bar". get("foo", 3): returns "bar" (latest value at or before time 3). set("foo", "bar2", 4): stores bar2 at time 4. get("foo", 4): returns "bar2". get("foo", 5): returns "bar2".
Need a Hint?
Edge Cases to Watch
- 빈 입력 구조
- 단일 요소 입력
- 큰 수치 범위
해결할 준비가 되셨나요?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
인터뷰 통찰력 및 변형
복잡성 분석 분석
왜 시간인가?: Directly evaluates all possibilities.
왜 우주인가?: Uses standard local memory.
왜 시간인가?: Optimized paths reduce total operations.
왜 우주인가?: May trade memory for speed.
최적화된 솔루션 Python 코드
최적화된 솔루션 Python 코드
class TimeMapOpt:
def __init__(self):
self.store = {}
def set(self, key: str, value: str, timestamp: int) -> None:
if key not in self.store: self.store[key] = []
self.store[key].append([value, timestamp])
def get(self, key: str, timestamp: int) -> str:
res = ""
values = self.store.get(key, [])
l, r = 0, len(values) - 1
while l <= r:
m = (l + r) // 2
if values[m][1] <= timestamp:
res = values[m][0]
l = m + 1
else:
r = m - 1
return res무차별 대입 코드(스포일러 보호)
무차별 대입 코드(스포일러 보호)
class TimeMapBrute:
def __init__(self):
self.store = {}
def set(self, key: str, value: str, timestamp: int) -> None:
if key not in self.store: self.store[key] = []
self.store[key].append([value, timestamp])
def get(self, key: str, timestamp: int) -> str:
res = ""
values = self.store.get(key, [])
for v, t in values:
if t <= timestamp: res = v
return resAlgorithm Pattern Checklist
When dealing with Binary Search data patterns.
- Are constraints clear?
- Is there a linear or logarithmic optimization possible?
Key Revision Notes
표준 이진 검색 문제 속성이 적용됩니다.
관련 질문
PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!
권장 Python 리소스
관련 대화형 튜토리얼, 치트 시트, 코드 비교를 통해 지식을 확장하세요.
Python Datetime
Python에서 날짜, 시간, 시간대 및 계산을 처리하는 방법을 알아보세요. 날짜/시간 및 timedelta를 사용하여 형식 지정, 구문 분석 및 산술을 마스터합니다.
Python에서 값을 기준으로 사전을 정렬하는 방법
값을 기준으로 Python 사전을 정렬하는 방법을 알아보세요. sorted(), 사용자 정의 키 람다 및 순서가 지정된 dict 구조를 사용하여 정렬을 살펴보세요.
Python DateTime 형식 지정 치트 시트
datetime, strftime 및 strptime을 사용하여 Python에서 날짜와 시간을 구문 분석하고 형식을 지정하는 방법을 알아보세요.
Python 대 JavaScript: 어떤 프로그래밍 언어가 가장 좋나요?
Python과 JavaScript를 포괄적으로 비교합니다. 구문 차이점, 성능, 사용 사례(백엔드와 프런트엔드) 및 코딩 예제를 살펴보세요.