문제
양의 정수 배열 nums과 양의 정수가 target이 주어지면 연속된 요소의 합으로 만들 수 있는 최소 길이를 반환합니다.
그러한 하위 배열이 없으면 0 을 반환하십시오.
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
Example 3:
Input: target = 11, nums = [1,1,1,1,1,1,1,1] Output: 0
Constraints:
1 <= target <= 10^9
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^4
접근방식 --> 실패
다른 풀이 및 회고
class Solution {
public int minSubArrayLen(int target, int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int left = 0;
int minLength = Integer.MAX_VALUE;
int currentSum = 0;
for (int right = 0; right < nums.length; right++) {
currentSum += nums[right];
while (currentSum >= target) {
minLength = Math.min(minLength, right - left + 1);
currentSum -= nums[left];
left++;
}
}
if (minLength != Integer.MAX_VALUE)
return minLength;
else
return 0;
}
}
목표한 타겟 이상의 합을 구하였을때 left, right 를 설정하여 연속된 배열을 설정하여 배열의 요소를 바꿔가면서 최소 길이를 구하는 방식이다.
Sliding Window 방식의 문제를 처음 접해보아서 실제로 잘 적용하지 못하였는데 개념을 한번 더 익히게 되었다.
'원티드 프리온보딩 - BE > 과제 정리' 카테고리의 다른 글
[LinkedList] 141. Linked List Cycle (500) | 2023.08.29 |
---|---|
[Sliding Window] 3. Longest Substring Without Repeating Characters (796) | 2023.08.28 |
[Two Pointers] 167. Two Sum II - Input Array Is Sorted (813) | 2023.08.26 |
[Two Pointers] 125. Valid Palindrome (780) | 2023.08.26 |
[Array/String] 55. Jump Game (1137) | 2023.08.24 |