zoukankan      html  css  js  c++  java
  • 862. Shortest Subarray with Sum at Least K

    Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K.

    If there is no non-empty subarray with sum at least K, return -1.

    Example 1:

    Input: A = [1], K = 1
    Output: 1
    

    Example 2:

    Input: A = [1,2], K = 4
    Output: -1
    

    Example 3:

    Input: A = [2,-1,2], K = 3
    Output: 3
    

    Note:

    1. 1 <= A.length <= 50000
    2. -10 ^ 5 <= A[i] <= 10 ^ 5
    3. 1 <= K <= 10 ^ 9

    Approach #1: prefix sum. [Time Limit Exceeded]

    class Solution {
    public:
        int shortestSubarray(vector<int>& A, int K) {
            int len = A.size();
            if (len == 1 && A[0] >= K) return 1;
            int step = INT_MAX;
            vector<int> prefixSum(len, 0);
            prefixSum[0] = A[0];
            for (int i = 1; i < len; ++i)
                prefixSum[i] = prefixSum[i-1] + A[i];
            for (int i = 0; i < len; ++i) {
                if (prefixSum[i] >= K) 
                    step = min(step, i+1);
                for (int j = i+1; j < len; ++j) {
                    if (prefixSum[j]-prefixSum[i] >= K) {
                        step = min(step, j-i);
                    }
                }
            }
            if (step == INT_MAX) return -1;
            else return step;
        }
    };
    

      

    Approach #2:  deque.

    class Solution {
    public:
        int shortestSubarray(vector<int>& A, int K) {
            int len = A.size();
            int res = len + 1;
            vector<int> sum(len+1, 0);
            for (int i = 0; i < len; ++i)
                sum[i+1] = sum[i] + A[i];
            deque<int> d;
            for (int i = 0; i < len+1; ++i) {
                while (!d.empty() && sum[i]-sum[d.front()] >= K) 
                    res = min(res, i-d.front()), d.pop_front();
                while (!d.empty() && sum[i] <= sum[d.back()])
                    d.pop_back();
                d.push_back(i);
            }
            return res <= len ? res : -1;
        }
    };
    

    Runtime: 144 ms, faster than 33.12% of C++ online submissions for Shortest Subarray with Sum at Least K.

    Analysis:

    deque Member functions


    Iterators:

    Capacity:

    Element access:

    Modifiers:

    Allocator:

    Non-member functions overloads

     
    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    SolarWinds Orion API 远程代码执行漏洞(CVE-2020-10148)
    Lanproxy 路径遍历漏洞 (CVE-2021-3019)
    公众号文章集合-2020整理回顾
    PHPMailer远程命令执行漏洞复现
    SaltStack Shell 注入 (CVE-2020-16846)漏洞
    (CVE-2020-7961)Liferay Portal RCE 反序列化命令执行漏洞
    (CVE-2020-17530)Struts2 S2-061 远程命令执行漏洞复现
    ora-01722 无效数字
    公开课平台推荐
    PL/SQL Developer如何导出数据成sql的insert语句
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9939890.html
Copyright © 2011-2022 走看看