From 5c5f32bd0a77591f41d28a524b53e63c384a2e5c Mon Sep 17 00:00:00 2001 From: gameloader Date: Thu, 14 Mar 2024 11:30:50 +0800 Subject: [PATCH] leetcode update --- content/posts/leetcode.md | 174 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 174 insertions(+) diff --git a/content/posts/leetcode.md b/content/posts/leetcode.md index 26aa282..46c7ed3 100644 --- a/content/posts/leetcode.md +++ b/content/posts/leetcode.md @@ -1042,3 +1042,177 @@ func pivotInteger(n int) int { ### 总结 查看他人解法发现本题其实也可以使用前缀和进行求解, 将每个下标位置处的前缀和求出并保存, 倒序遍历数组, 将后面的数的和与当前位置的前缀和比较即可, 示例代码 + +## day17 2024-03-14 + +### 930. Binary Subarrays With Sum + +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 + +### 题解 + +本题可以用前缀和求解, 类似这种求数组中连续和的问题都可以用前缀和求解, 首先计算出所有位置上的前缀和, 使用滑动窗口遍历前缀和数组, 根据goal的值调整窗口的左右边界, 注意0需要特殊处理, 0是否存在不影响整个序列的和, 0所在的位置处的前缀和和前面的元素相同. + +### 代码 + +```go +func numSubarraysWithSum(nums []int, goal int) int { + + sum := 0 + + prefixsum := []int{0} + + for _,value := range nums{ + + sum += value + + prefixsum = append(prefixsum, sum) + + } + + front := 1 + + back := 0 + + flag := 0 + + result := 0 + + for front < len(prefixsum){ + + if prefixsum[front] - prefixsum[back]goal{ + + if front-1 == back{ + + front++ + + } + + back++ + + }else{ + + if (front-1 == back){ + + result++ + + front++ + + back = flag + + }else if prefixsum[back] == prefixsum[back+1]{ + + result++ + + back++ + + }else if (front goal { + + sum -= nums[left] + + left++ + + } + + ans += right - left + 1 + + } + + return ans + +} +```