2024/11/20 灵茶题单 二分查找
This commit is contained in:
parent
858e0d3c3b
commit
5be812483c
|
@ -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<String, List<Integer>> timeMap;
|
||||||
|
private final Map<String, List<String>> 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<Integer> timeList = timeMap.get(key);
|
||||||
|
List<String> valueList = valueMap.get(key);
|
||||||
|
int index = binarySearch(timeList, timestamp + 1) - 1;
|
||||||
|
if (index < 0) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return valueList.get(index);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private int binarySearch(List<Integer> 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;
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue