Q:输入一个正整数数组,求数组中和不小于K的连续子数组的最短长度,不存在返回0
凡是涉及到数据的题 ,我们都可以套用双端指针这种思路,只不过不同的业务场景,需要灵活点
在之前的题目中,
双端指针分别指向了全局数组的两端,而在这道题中,双端则指向了局部数组的两端,
一个指针控制数据的膨胀(hotIndex),一个指针控制数的塌陷(coolIndex)
ok,貌似这种思路有种叫法 【滑动窗口】
综上所述,代码如下
public static void main(String[] args) {
int k = 7;
int [] array = new int []{5,1,4,3};
System.out.println(getShortest(array,k));
}
private static int getShortest(int[] array, int k) {
int sum = 0 ;
int coolIdx = 0;
int count = Integer.MAX_VALUE;
//膨胀指针只负责膨胀
for (int hotIdx = 0;hotIdx < array.length; hotIdx++) {
sum = sum + array[hotIdx];
while (coolIdx<= hotIdx && sum >= k){
count = Math.min(count,hotIdx-coolIdx+1);
//核心在这里,这里就表达了向左减少数字,实现局部数组塌陷
sum = sum - array[coolIdx++];
}
}
return count;
}
从这道题还可以衍生一些变种问题
Q:输入一个正整数数组,请问数组中有多少个数字乘积小于k的连续子数组?
依旧可以采用上述膨胀塌陷的思路【滑动窗口】解决问题
public static void main(String[] args) {
int k = 100;
int [] array = new int []{10,5,2,6};
System.out.println(getArray(array,k));
}
private static int getArray(int[] array, int k) {
int product = 1 ;
int coolIdx = 0;
int count = 0;
for (int hotIdx = 0;hotIdx < array.length; hotIdx++) {
product = product* array[hotIdx];
while (coolIdx<= hotIdx && product >= k){
//核心在这里,这里就表达了向左减少数字,实现当前数组缩减
product = product / array[coolIdx++];
}
count = count+ (hotIdx>= coolIdx? hotIdx - coolIdx +1:0);
}
return count;
}