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

(constructor)
Construct deque container (public member function )
(destructor)
Deque destructor (public member function )
operator=
Assign content (public member function )

Iterators:

begin
Return iterator to beginning (public member function )
end
Return iterator to end (public member function )
rbegin
Return reverse iterator to reverse beginning (public member function )
rend
Return reverse iterator to reverse end (public member function )
cbegin 
Return const_iterator to beginning (public member function )
cend 
Return const_iterator to end (public member function )
crbegin 
Return const_reverse_iterator to reverse beginning (public member function )
crend 
Return const_reverse_iterator to reverse end (public member function )

Capacity:

size
Return size (public member function )
max_size
Return maximum size (public member function )
resize
Change size (public member function )
empty
Test whether container is empty (public member function )
shrink_to_fit 
Shrink to fit (public member function )

Element access:

operator[]
Access element (public member function )
at
Access element (public member function )
front
Access first element (public member function )
back
Access last element (public member function )

Modifiers:

assign
Assign container content (public member function )
push_back
Add element at the end (public member function )
push_front
Insert element at beginning (public member function )
pop_back
Delete last element (public member function )
pop_front
Delete first element (public member function )
insert
Insert elements (public member function )
erase
Erase elements (public member function )
swap
Swap content (public member function )
clear
Clear content (public member function )
emplace 
Construct and insert element (public member function )
emplace_front 
Construct and insert element at beginning (public member function )
emplace_back 
Construct and insert element at the end (public member function )

Allocator:

get_allocator
Get allocator (public member function )

Non-member functions overloads

relational operators
Relational operators for deque (function )
swap
Exchanges the contents of two deque containers (function template )

原文地址:https://www.cnblogs.com/ruruozhenhao/p/9939890.html

时间: 2024-08-28 14:54:25

862. Shortest Subarray with Sum at Least K的相关文章

lc 862. Shortest Subarray with Sum at Least K

断网导致原来写的那么多答案全没了,博客园能不能实时保存草稿,醉. https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/ 给一个数组a,找和大于k的所有子数组中的最短的那个. 最近二分有点上头,因为的确很强大,两个考虑二分的情况(其实需要刻意去想想能不能使用二分才会想到,这会是个好习惯): 1.最优问题变判断问题.比如:行递增列递增的矩阵中找某个元素->行递增列递增的矩阵中找第k大元素 2.有相应的简单孪生问题.比

[Swift]LeetCode862. 和至少为 K 的最短子数组 | 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 Exa

leetcode 862 shorest subarray with sum at least K

https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/ 首先回顾一下求max子数组的值的方法是:记录一个前缀min值,然后扫一遍sum数组. 1.首先这里不需要最大,因为刚好够k就好了 2.这里需要距离最短.就是数组的长度最短. 这里的思路也一样,不过保存很多个min值,就是用一个队列,保存前缀的min值,不需要最min,只不过有更小的就更好. 也就是如果sum数组的值是: ..... 60, 40.....Y..

array / matrix subarray/submatrix sum

Maximal Subarray Sum : O(n) scan-and-update dynamic programming,https://en.wikipedia.org/wiki/Maximum_subarray_problem, https://leetcode.com/problems/maximum-subarray Shortest Subarray Sum Equals K : prefix-sum + sort + hash-table: O(nlogn) time, O(n

LeetCode 1099. Two Sum Less Than K

原题链接在这里:https://leetcode.com/problems/two-sum-less-than-k/ 题目: Given an array A of integers and integer K, return the maximum S such that there exists i < j with A[i] + A[j] = S and S < K. If no i, jexist satisfying this equation, return -1. Example

[LC] 1099. Two Sum Less Than K

Given an array A of integers and integer K, return the maximum S such that there exists i < j with A[i] + A[j] = S and S < K. If no i, j exist satisfying this equation, return -1. Example 1: Input: A = [34,23,1,24,75,33,54,8], K = 60 Output: 58 Expl

单调栈与单调队列

单调栈 特点 栈内的元素单调递增或者单调递减,可以在\(O(n)\)的时间内求出数列中所有数的左边或右边第一个比其大或小的元素,总时间复杂度为\(O(n)\) 例子 单调栈中一般存索引 一个单调递增栈s = [0, 10, 20 ,t]代表栈中a[1]~a[9]的元素大于a[10]的元素,索引为a[11]~a[19]的元素大于a[20]的元素... 这样我们可以发现在a[10]左边第一个比a[10]的数为a[0],在a[20]左边第一个比a[20]的数为a[10]... 如何实现呢? 每次有元素

【LeetCode】二分 binary_search(共58题)

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [4]Median of Two Sorted Arrays [29]Divide Two Integers [33]Search in Rotated Sorted Array [34]Find First and Last Position of Element in Sorted Array [35]Search Insert Position [50]Pow(

【LeetCode】队列 queue(共8题)

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [346]Moving Average from Data Stream [353]Design Snake Game [363]Max Sum of Rectangle No Larger Than K [582]Kill Process [621]Task Scheduler [622]Design Circular Queue [641]Design Circu