2024/11/21 灵茶题单 二分查找

This commit is contained in:
Cool 2024-11-21 12:41:21 +08:00
parent 5be812483c
commit 017b078a85
1 changed files with 64 additions and 0 deletions

View File

@ -0,0 +1,64 @@
package com.cool.ling_cha_mount.binary_search;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Num1146 {
@Test
public void test() {
SnapshotArray snapshotArray = new SnapshotArray(4);
snapshotArray.snap();
snapshotArray.snap();
snapshotArray.get(3, 1);
snapshotArray.set(2, 4);
snapshotArray.snap();
snapshotArray.set(1, 4);
}
}
class SnapshotArray {
private int snap = 0;
private final Map<Integer, List<int[]>> map = new HashMap<>();
public SnapshotArray(int length) {
}
public void set(int index, int val) {
map.computeIfAbsent(index,key->new ArrayList<>()).add(new int[]{snap,val});
}
public int snap() {
return this.snap++;
}
public int get(int index, int snap_id) {
if(!map.containsKey(index)){
return 0;
}
List<int[]>list=map.get(index);
int i=binarySearch(list,snap_id);
return i>=0?list.get(i)[1]:0;
}
private int binarySearch(List<int[]>list,int target) {
int left=-1;
int right=list.size();
while(left+1<right){
int mid=(left+right)>>>1;
if(list.get(mid)[0]>target){
right=mid;
}else{
left=mid;
}
}
return left;
}
}