leetcode862题,和至少为 K 的最短子数组。
用p[i]用来表示前i-1个元素的和。这道题目的是求满足p[y]-p[x]>=K的情况下的最小y-x。看了官方解析,用C的实现照搬一下,是一个没有灵魂的搬运工。
如下是理解:
用一个队列把“可能的x”存起来,每次都去看当前y-x的比较值,看下当前的长度大小。用queue存储可能的x。这个x的特点是:1、不会是负数;2、如果对某个y,y-x是他的最短距离,那么后面的y如果有最短距离,如果是x,肯定不是最后需要的答案。
假定对当前y,如果他的前一个p(y-1)跟py比,py变小了,那么这个(y-1)肯定不是“可能的x”,所以y-1出队;
假定对当前y,如果满足py-p(xhead)>=K,那么就往后找找,head++,尽可能往后找。
#define MAXLEN 60000
int shortestSubarray(int* A, int ASize, int K){
int i, y, finalcount = ASize + 1;
int head, tail;
int queue[MAXLEN];
head = tail = 0;
int *p = (int*) malloc(sizeof(int) * (ASize + 1));
p[0] = 0;
for (i = 1; i <= ASize; i++) {
p[i] = p[i-1] + A[i-1];
}
for (y = 0; y <= ASize; y++) {
while (head != tail && p[y] <= p[queue[tail - 1]]) {
tail--;
}
while (head != tail && (p[y] - p[queue[head]] >= K)) {
finalcount = finalcount > y - queue[head] ? y - queue[head] : finalcount ;
head ++;
}
queue[tail++] = y;
}
if (finalcount == ASize + 1) {
finalcount = -1;
}
return finalcount;
}
其实早上写了个简单的方法,但是用例数多了,死活不过,超出时间限制,果然还是无法靠自己灵巧的脑细胞啊。
int shortestSubarray(int* A, int ASize, int K){
int i, j, sum, count, finalcount = -1;
int start, end;
for (start = 0; start < ASize; start ++) {
sum = A[start];
count = 1;
if (sum >= K) {
return count;
}
for (end = start + 1; end < ASize; end ++) {
sum = sum + A[end];
count++;
if (sum < K) {
continue;
}
if (finalcount == -1) {
finalcount = count;
} else if (finalcount > count) {
finalcount = count;
}
break;
}
}
return finalcount;
}