209. Minimum Size Subarray Sum
Medium
Given an array of positive integers nums
and a positive integer target
, return the minimal length of a subarray whose sum is greater than or equal to target
. If there is no such subarray, return 0
instead.
Example 1:
Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.
Example 2:
Input: target = 4, nums = [1,4,4]
Output: 1
Constraints:
1 <= target <= 109
1 <= nums.length <= 105
1 <= nums[i] <= 104
Follow up: If you have figured out the
O(n)
solution, try coding another solution of which the time complexity is O(n log(n))
.๋ฌธ์ ์ ๊ทผ๋ฒ
ํ์ ๋ฐฐ์ด์ ํฉ์ด target๋ณด๋ค ํฌ๊ฑฐ๋ ๊ฐ์๊ฒฝ์ฐ ํ์ ๋ฐฐ์ด์ ์ต์ ๊ธธ์ด๋ฅผ ๋ฆฌํดํ๋ ๋ฌธ์ ์
๋๋ค.
ํ์ ๋ฐฐ์ด์ ํฉ์ ๊ตฌํ๋ ๋ฌธ์ ์ด๊ธฐ ๋๋ฌธ์ ์ฌ๋ผ์ด๋ฉ ์๋์ฐ ๊ธฐ๋ฒ์ ์ฌ์ฉํ์ฌ ํ์์ต๋๋ค.
1. window์ ์์์์น๋ฅผ ๋ํ๋ด๋ left์ ๊ฒฐ๊ณผ๊ฐ ans, ํ์ ๋ฐฐ์ด์ ํฉ์ ์ ์ฅํ sum ๋ณ์๋ฅผ ์ด๊ธฐํ ํด์ค๋ค.
2. ์ฃผ์ด์ง nums๋ฅผ for๋ฌธ์ผ๋ก ์ํํ๋ฉด์ ๊ฐ์ sum์ ๋ํด์ค๋ค.
3. sum >= target ์ธ๊ฒฝ์ฐ (while)
- ํ์ ๋ฐฐ์ด์ ๊ธธ์ด๋ฅผ ans์ ์ฌํ ๋น ํด์ค๋ค.
- window ์ฌ์ด์ฆ๋ฅผ ์ด๊ณผํ๊ธฐ ๋๋ฌธ์ sum -= nums[left++] (์ด๋ window ๊ธฐ์ค์ ํ์ ๋ฐฐ์ด์ ํฉ์ด target ๋ณด๋ค ํฌ๊ฑฐ๋ ๊ฐ์ ๊ฒฝ์ฐ์ ๋๋ค. )
4. ํ์ ๋ฐฐ์ด์ ํฉ์ด ์กฐ๊ฑด์ ๋ง์ง ์์ ๊ฒฝ์ฐ (ans === Infinity) 0์ ๋ฆฌํดํด์ค๋ค. ์๋ ๊ฒฝ์ฐ ans ๋ฆฌํด
/**
* @param {number} target
* @param {number[]} nums
* @return {number}
*/
var minSubArrayLen = function(target, nums) {
let left = 0, ans = Infinity, sum = 0;
for (let right = 0; right < nums.length; right++) {
sum+= nums[right]
// window ์ด๊ณผ
// ํ์ ๋ฐฐ์ด์ ํฉ์ด target ๋ณด๋ค ํฌ๊ฑฐ๋ ๊ฐ์๋ ํ์ ๋ฐฐ์ด์ ๊ธธ์ด๋ฅผ ์
๋ฐ์ดํธ ํด์ค๋ค.
while (sum >= target) {
ans = Math.min(ans, right+1-left)
sum -= nums[left++]
}
}
return ans === Infinity ? 0 : ans;
};
'๐ Study Note > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
1091. Shortest Path in Binary Matrix (0) | 2023.02.06 |
---|---|
2091. Removing Minimum and Maximum From Array (0) | 2023.02.01 |
346. Moving Average from Data Stream (0) | 2022.12.26 |
2225. Find Players With Zero or One Losses (0) | 2022.11.28 |
967. Numbers With Same Consecutive Differences (0) | 2022.11.26 |