forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
minimum-size-subarray-sum.cpp
46 lines (44 loc) · 1.42 KB
/
minimum-size-subarray-sum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Time: O(n)
// Space: O(1)
// Sliding window solution.
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int start = -1, sum = 0, min_size = numeric_limits<int>::max();
for (int i = 0; i < nums.size(); ++i) {
sum += nums[i];
while (sum >= s) {
min_size = min(min_size, i - start);
sum -= nums[++start];
}
}
if (min_size == numeric_limits<int>::max()) {
return 0;
}
return min_size;
}
};
// Time: O(nlogn)
// Space: O(n)
// Binary search solution.
class Solution2 {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int min_size = numeric_limits<int>::max();
vector<int> sum_from_start(nums.size() + 1);
partial_sum(nums.cbegin(), nums.cend(), sum_from_start.begin() + 1);
for (int i = 0; i < nums.size(); ++i) {
const auto& end_it = lower_bound(sum_from_start.cbegin() + i,
sum_from_start.cend(),
sum_from_start[i] + s);
if (end_it != sum_from_start.cend()) {
int end = static_cast<int>(end_it - sum_from_start.cbegin());
min_size = min(min_size, end - i);
}
}
if (min_size == numeric_limits<int>::max()) {
return 0;
}
return min_size;
}
};