From 5be812483c7865814a8c929c29d148624d09d69a Mon Sep 17 00:00:00 2001 From: Cool <747682928@qq.com> Date: Wed, 20 Nov 2024 16:37:19 +0800 Subject: [PATCH] =?UTF-8?q?2024/11/20=20=E7=81=B5=E8=8C=B6=E9=A2=98?= =?UTF-8?q?=E5=8D=95=20=E4=BA=8C=E5=88=86=E6=9F=A5=E6=89=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ling_cha_mount/binary_search/Num981.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/main/java/com/cool/ling_cha_mount/binary_search/Num981.java diff --git a/src/main/java/com/cool/ling_cha_mount/binary_search/Num981.java b/src/main/java/com/cool/ling_cha_mount/binary_search/Num981.java new file mode 100644 index 0000000..cc3fcef --- /dev/null +++ b/src/main/java/com/cool/ling_cha_mount/binary_search/Num981.java @@ -0,0 +1,53 @@ +package com.cool.ling_cha_mount.binary_search; + +import java.util.*; +import java.util.stream.Collectors; + +public class Num981 { + + +} + +class TimeMap { + + private final Map> timeMap; + private final Map> valueMap; + + public TimeMap() { + timeMap = new HashMap<>(); + valueMap = new HashMap<>(); + } + + public void set(String key, String value, int timestamp) { + timeMap.computeIfAbsent(key, e -> new ArrayList<>()).add(timestamp); + valueMap.computeIfAbsent(key, e -> new ArrayList<>()).add(value); + } + + public String get(String key, int timestamp) { + if (!timeMap.containsKey(key)) { + return ""; + } + List timeList = timeMap.get(key); + List valueList = valueMap.get(key); + int index = binarySearch(timeList, timestamp + 1) - 1; + if (index < 0) { + return ""; + } + return valueList.get(index); + + } + + private int binarySearch(List list, int target) { + int left = -1; + int right = list.size(); + while (left + 1 < right) { + int mid = (left + right) >>> 1; + if (list.get(mid) >= target) { + right = mid; + } else { + left = mid; + } + } + return right; + } +}