2024/11/17 灵茶题单 二分查找
This commit is contained in:
parent
b5c1126d7d
commit
0683d87b58
|
@ -0,0 +1,39 @@
|
|||
package com.cool.ling_cha_mount.binary_search;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class RangeFreqQuery {
|
||||
|
||||
private final Map<Integer, List<Integer>> map = new HashMap<>();
|
||||
|
||||
public RangeFreqQuery(int[] arr) {
|
||||
for (int i = 0; i < arr.length; i++) {
|
||||
map.computeIfAbsent(arr[i], k -> new ArrayList<>()).add(i);
|
||||
}
|
||||
}
|
||||
|
||||
public int query(int left, int right, int value) {
|
||||
List<Integer> list = map.get(value);
|
||||
if (list == null) {
|
||||
return 0;
|
||||
}
|
||||
return binarySearch(list, right + 1) - binarySearch(list, left);
|
||||
}
|
||||
|
||||
private int binarySearch(List<Integer> list, int target) {
|
||||
int left = 0;
|
||||
int right = list.size() - 1;
|
||||
while (left <= right) {
|
||||
int mid = (right - left) / 2 + left;
|
||||
if (list.get(mid) >= target) {
|
||||
right = mid - 1;
|
||||
} else {
|
||||
left = mid + 1;
|
||||
}
|
||||
}
|
||||
return left;
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue