Subarray Sum II
Last updated
Last updated
public int subarraySumII(int[] A, int start, int end) {
int[] sum = new int[A.length + 1];
int count = 0;
for(int i = 1; i <= A.length; i++){
sum[i] = sum[i-1] + A[i-1];
}
for(int i = 1; i <= A.length; i++){
//固定尾端为i,传入数组长度为I,所以要有I做参数,和window相比,window固定头
int lowBound = find(A, i, sum[i] - end);
int highBound = find(A, i, sum[i] - start + 1);
count += highBound - lowBound;
}
return count;
}
//target <= j
private int find(int[] A, int len, int target){
if(A[len -1] < target)
return len;
int start = 0, end = len - 1, first = 0;
while(start + 1 < end){
int mid = start + (end - start)/2;
if(A[mid] >= target){
//first = mid;
end = mid;
}else {
start = mid;
}
}
if(A[start] >= target){
return start;
}
if(A[end] >= target){
return end;
}
return end;
} public int subarraySumII(int[] A, int start, int end) {
int head = 0, ft = 0, st = 0, n = A.length, sf = 0, ss = 0, count = 0;
for(int i = 0; i < n; i++){
while(ft < n && sf + A[ft] < start){
ft ++;
sf += A[ft];
}
//第二指针不能低于第一指针
if(st < ft){
st = ft;
ss = sf;
}
while(st < n && ss + A[st] <= end){
st ++;
ss += A[st];
}
count += (st - ft);
sf -= A[i];
ss -= A[i];
}
return count;
}