public class 连续和不小于S的最短子序列 {
static int S = 15;
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = {5, 1, 3, 5, 10, 7, 4, 9, 2, 8};
int sum = 0;
int begin = 0;
int end =0;
int left = 0;
int right = -1;
int min = arr.length-1;
while(true) {
while(right<arr.length-1&&sum<S) {//注意边界问题,这里可以防止数组越界
sum += arr[++right];//移动右端点,直到sum大于等于S
}
if(sum<S) break;//while循环出口
end =right;
min = Min(min,end - begin +1);//找到满足条件且相对较小的区间长度,
sum -= arr[left++];//通过外层while循环移动左端点
begin = left;
}
System.out.println(min);
}
public static int Min(int a,int b) {
if(a>b) {
return b;
}
else return a;
}
}
总和不小于S的连续子序列的长度的最小值-尺取法
最新推荐文章于 2024-08-12 08:34:57 发布