
思路:
- 建模:求子區(qū)間個數(shù),子區(qū)間的要求:存在某數(shù)出現(xiàn)過t次以上;
- 記錄某數(shù)出現(xiàn)次數(shù)用hashmap最佳;犧牲一定的空間復(fù)雜度換取時間復(fù)雜度。
代碼:
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int t = sc.nextInt();
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = sc.nextInt();
}
int result = 0;
for (int i = 0; i <= array.length - k; i++) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
recordinfo(map, array, i, i + k);
result += isAppearThanT(map, t);
}
System.out.println(result);
}
private static void recordinfo(HashMap<Integer, Integer> map, int[] array, int low, int high) {
for (int i = low; i < high; i++) {
if (map.containsKey(array[i])) {
int temp = map.get(array[i]);
map.put(array[i], temp + 1);
} else {
map.put(array[i], 1);
}
}
}
private static int isAppearThanT(HashMap<Integer, Integer> map, int t) {
int a = 0;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() >= t) {
a++;
}
}
return a;
}
}