題目
思路
O(n)的思路比較簡單,直接用兩個下標掃一遍即可;
O(nLogn)有點難,個人感覺應該是先得到Sum[i](前i+1)個數的和,因為數字都是正數,那麼Sum數組可以用二分查找。我們掃一遍Sum,再二分查找符合條件的前一個Sum的位置即可。<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxwPjxzdHJvbmc+tPrC6zwvc3Ryb25nPjxiciAvPg0KTyhuKaO6PC9wPg0KPHByZSBjbGFzcz0="brush:java;">
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];
if (head > tail) tail = head;
}
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;
}