# C solution, both O(n) & O(nLogn)

• O(n):

``````int minSubArrayLen(int s, int * nums, int numsSize) {
int sum = nums[0], head = 0, tail = 0, minL = numsSize + 1;
while (tail < numsSize) {
if (tail - head + 1 < minL && sum >= s) minL = tail - head + 1;
if (sum >= s) sum -= nums[head++];
else sum += nums[++tail];
}
return minL == numsSize + 1 ? 0 : minL;
}
``````

O(nLogn):

``````// 在不下降的序列中寻找恰好比target小的数出现位置，也即最后一个比target小的数出现的位置
// search a number that is exactly less than 'target', which means the last number less than 'target'
int binarySearchIncreaseLastSmaller(int l, int r, int target, int * nums) {
if (l >= r) return -1;
while (l < r - 1) {
int m = l + ((r - l) >> 1);
if (nums[m] < target) l = m;
else r = m - 1;
}
if (nums[r] < target) return r;
else if (nums[l] < target) return l;
else return -1;
}

int minSubArrayLen(int s, int * nums, int numsSize) {
int * Sum = (int*)malloc(sizeof(int) * (numsSize + 1)), minL = numsSize + 1;
Sum[0] = 0;
for (int i = 1; i <= numsSize; i++) Sum[i] = Sum[i - 1] + nums[i - 1];
for (int i = 1; i <= numsSize; i++) {
if (Sum[i] >= s) {
int k = Sum[i];
int BeforePos = binarySearchIncreaseLastSmaller(0, i, Sum[i] - s + 1, Sum);
if (BeforePos != -1 && i - BeforePos < minL) minL = i - BeforePos;
}
}
return minL == numsSize + 1 ? 0 : minL;
}``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.