본문 바로가기
알고리즘 풀이

240314 LeetCode 문제 풀이

by 미노킴 2024. 3. 14.

930. Binary Subarrays With Sum

https://leetcode.com/problems/binary-subarrays-with-sum/description/?envType=daily-question&envId=2024-03-14

 

1) 문제 설명

Given a binary array nums and an integer goal, return the number of non-empty subarrays with a sum goal.

A subarray is a contiguous part of the array.

 

Example 1:

Input: nums = [1,0,1,0,1], goal = 2
Output: 4
Explanation: The 4 subarrays are bolded and underlined below:
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]

Example 2:

Input: nums = [0,0,0,0,0], goal = 0
Output: 15

 

2) 제한 사항

  • 1 <= nums.length <= 3 * 104
  • nums[i] is either 0 or 1.
  • 0 <= goal <= nums.length

 

3) 도전 과제

X

 

4) 풀이

못 풀어서 다른 사람의 풀이를 참조하였다.

 

투 포인터를 이용하여 모든 부분 배열에 대해 결과를 조사한다.

 

5) 소스 코드 및 결과

class Solution {
    public int numSubarraysWithSum(int[] nums, int goal) {
        int i = 0, count = 0, res = 0;
        for (int j = 0; j < nums.length; ++j) {
            if (nums[j] == 1) {
                goal--;
                count = 0;
            }
            
            while (goal == 0 && i <= j) {
                goal += nums[i];
                i++;
                count++;
                if (i > j - goal + 1)
                    break;
            }
            
            while (goal < 0) {
                goal += nums[i];
                i++;
            }
            
            res += count;
        }
        return res;
    }
}

6) 다른 사람의 풀이

 
X

'알고리즘 풀이' 카테고리의 다른 글

240322 LeetCode 문제 풀이  (0) 2024.03.22
240321 LeetCode 문제 풀이  (0) 2024.03.21
240313 LeetCode 문제 풀이  (0) 2024.03.13
240311 LeetCode 문제 풀이  (0) 2024.03.11
240308 LeetCode 문제 풀이  (0) 2024.03.09