程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> LeetCode Minimum Size Subarray Sum

LeetCode Minimum Size Subarray Sum

編輯:關於C++

題目
這裡寫圖片描述

思路
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;
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved