iT邦幫忙

2024 iThome 鐵人賽

DAY 21
0

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.


題目給我們一組數列,目標是返回所有由0組成的子數列的數量!

我的解題思路:

  • 子數列是數列中連續的數
  1. 重頭開始遍歷數列
  2. 看到0再開始紀錄有連續幾個0
  3. 因為題目沒有說要排除重複的組合
  4. 所以每個0的數列都要計算
  5. 遍歷完數列後返回0子數列的數量
  • 題目範例 :
    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.

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

        // 開始遍歷
        for (int num : nums) {
            if (num == 0) {
                count++;
                result += count;
            } else{
                // 如果數字不是 0,
                count =0;
            }
        }
        return result;
    }
}

因為之前已經寫過幾次跟計算子數列有關的題目,加上題目跟之前比起來也算簡單~
所以這次有經驗就寫比較順!話說不知不覺鐵人賽已經開始三週了,時間過真快。
https://ithelp.ithome.com.tw/upload/images/20241005/20169432n1MVECtjxK.png


上一篇
day-20[medium.491]nun-decreasing subsequences
下一篇
day-22[medium.2434]using a robot to print the lexicographically smallest string
系列文
轉生理工組後從零開始的leetcode刷題30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言