码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Minimum Size Subarray Sum

时间:2015-05-13 07:40:25      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

题目
技术分享

思路
O(n)的思路比较简单,直接用两个下标扫一遍即可;
O(nLogn)有点难,个人感觉应该是先得到Sum[i](前i+1)个数的和,因为数字都是正数,那么Sum数组可以用二分查找。我们扫一遍Sum,再二分查找符合条件的前一个Sum的位置即可。

代码
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];
        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;
}

LeetCode Minimum Size Subarray Sum

标签:

原文地址:http://blog.csdn.net/u012925008/article/details/45687715

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!