Last active
August 29, 2015 14:25
-
-
Save junjiah/7869ecfdf04ae607d160 to your computer and use it in GitHub Desktop.
solved 'Minimum Size Subarray Sum' on leetcode https://leetcode.com/problems/minimum-size-subarray-sum/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cassert> | |
#include <climits> | |
#include <iostream> | |
#include <vector> | |
using namespace std; | |
// Inspired from | |
// https://leetcode.com/discuss/42143/4ms-solution-and-nlogn-solution-with-detailed-explanations | |
class Solution { | |
public: | |
int minSubArrayLen(int s, vector<int>& nums) { | |
int start = 0, res = INT_MAX, curr_sum = 0; | |
for (int i = 0, len = nums.size(); i < len; ++i) { | |
curr_sum += nums[i]; | |
while (curr_sum >= s) { | |
res = min(res, i - start + 1); | |
curr_sum -= nums[start++]; | |
} | |
} | |
return res == INT_MAX ? 0 : res; | |
} | |
}; | |
int main() { | |
Solution sol; | |
vector<int> nums; | |
int res; | |
nums = {1, 6}; | |
res = sol.minSubArrayLen(100, nums); | |
assert(res == 0); | |
nums = {1, 6}; | |
res = sol.minSubArrayLen(2, nums); | |
assert(res == 1); | |
nums = {1, 2, 3}; | |
res = sol.minSubArrayLen(6, nums); | |
assert(res == 3); | |
nums = {2, 3, 1, 2, 4, 3}; | |
res = sol.minSubArrayLen(7, nums); | |
assert(res == 2); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
# @param {integer} s | |
# @param {integer[]} nums | |
# @return {integer} | |
def minSubArrayLen(self, s, nums): | |
prev, curr, nums_len = 0, 0, len(nums) | |
# Accumulator to compare with s. | |
acc = 0 | |
# Result. | |
min_cnt = nums_len + 1 | |
while True: | |
if acc < s: | |
# End of story. | |
if curr == nums_len: | |
break | |
# Can only move forward `curr`. | |
acc += nums[curr] | |
curr += 1 | |
else: | |
# Move `prev` forward until accumulator is | |
# smaller than s. | |
while prev < curr and acc >= s: | |
acc -= nums[prev] | |
prev += 1 | |
# Compare with previous result. | |
new_cnt = curr - prev + 1 | |
if new_cnt < min_cnt: | |
min_cnt = new_cnt | |
return 0 if min_cnt == nums_len + 1 else min_cnt | |
if __name__ == '__main__': | |
sol = Solution() | |
nums, s = [1, 6], 2 | |
assert sol.minSubArrayLen(s, nums) == 1 | |
nums, s = [1, 2, 3], 6 | |
assert sol.minSubArrayLen(s, nums) == 3 | |
nums, s = [2, 3, 1, 2, 4, 3], 7 | |
assert sol.minSubArrayLen(s, nums) == 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment