반응형

https://leetcode.com/problems/number-of-zero-filled-subarrays/description/

 

Number of Zero-Filled Subarrays - LeetCode

Can you solve this real interview question? Number of Zero-Filled Subarrays - Given an integer array nums, return the number of subarrays filled with 0. A subarray is a contiguous non-empty sequence of elements within an array.   Example 1: Input: nums =

leetcode.com


문제

Given an integer array nums, return the number of subarrays filled with 0.

A subarray is a contiguous non-empty sequence of elements within an array.

 

Example 1:

Input: nums = [1,3,0,0,2,0,0,4]
Output: 6
Explanation: 
There are 4 occurrences of [0] as a subarray.
There are 2 occurrences of [0,0] as a subarray.
There is no occurrence of a subarray with a size more than 2 filled with 0. Therefore, we return 6.

Example 2:

Input: nums = [0,0,0,2,0,0]
Output: 9
Explanation:
There are 5 occurrences of [0] as a subarray.
There are 3 occurrences of [0,0] as a subarray.
There is 1 occurrence of [0,0,0] as a subarray.
There is no occurrence of a subarray with a size more than 3 filled with 0. Therefore, we return 9.

Example 3:

Input: nums = [2,10,2019]
Output: 0
Explanation: There is no subarray filled with 0. Therefore, we return 0.

 

Constraints:

  • 1 <= nums.length <= 105
  • -109 <= nums[i] <= 109

풀이

풀이 과정

-109 부터 109 까지의 정수로 이루어진 배열 nums가 주어질 때 0으로 채워진 부분배열의 총 개수를 구하는 문제이다.

길이가 N인 배열의 부분배열의 개수는 1부터 N까지의 합을 구하는 것과 같다.

배열 부분배열의 개수
[0] 1
[0, 0] 3
[0, 0, 0] 6
[0, 0, 0, 0] 10

 

따라서 nums 배열의 요소를 순차적으로 탐색하며 0으로 이루어진 부분배열의 길이를 구해가며 그 길이를 정답에 계속 더해나간다.


최종 코드

class Solution {
    public long zeroFilledSubarray(int[] nums) {
        long answer = 0;

        // 0으로 채워진 배열의 길이
        long length = 0;
        
        // nums 배열의 모든 요소 탐색
        for(int i = 0; i < nums.length; i++) {
            // 현재 탐색 요소가 0인 경우
            // 0으로 채워진 배열의 길이 증가 및 길이만큼 정답 카운트 증가
            if(nums[i] == 0) {
                length++;
                answer += length;
            }
            // 현재 탐색 요소가 0이 아닌 경우 0으로 채워진 배열의 길이 초기화
            else length = 0;
        }

        return answer;
    }
}

 

HYOJUN