diff --git a/animation-simulation/前缀和/leetcode523连续的子数组和.md b/animation-simulation/前缀和/leetcode523连续的子数组和.md index c84d13b..68aa0de 100644 --- a/animation-simulation/前缀和/leetcode523连续的子数组和.md +++ b/animation-simulation/前缀和/leetcode523连续的子数组和.md @@ -101,3 +101,35 @@ public: }; ``` +Go Code: + +```go +func checkSubarraySum(nums []int, k int) bool { + m := map[int]int{} + // 由于前缀和%k可能为0,所以需要给出没有元素的时候,索引位置,即-1 + m[0] = -1 + sum := 0 + for i, num := range nums { + sum += num + key := sum % k + /* + // 题目中告诉k >= 1 + key := sum + if k != 0 { + key = sum % k + } + */ + if v, ok := m[key]; ok { + if i - v >= 2 { + return true + } + // 避免更新最小索引 + continue + } + // 保存的是最小的索引 + m[key] = i + } + return false +} +``` + diff --git a/animation-simulation/前缀和/leetcode560和为K的子数组.md b/animation-simulation/前缀和/leetcode560和为K的子数组.md index cf52022..cf9c9c3 100644 --- a/animation-simulation/前缀和/leetcode560和为K的子数组.md +++ b/animation-simulation/前缀和/leetcode560和为K的子数组.md @@ -183,3 +183,24 @@ public: }; ``` +Go Code: + +```GO +func subarraySum(nums []int, k int) int { + m := map[int]int{} + // m存的是前缀和,没有元素的时候,和为0,且有1个子数组(空数组)满足条件,即m[0] = 1 + m[0] = 1 + sum := 0 + cnt := 0 + for _, num := range nums { + sum += num + if v, ok := m[sum - k]; ok { + cnt += v + } + // 更新满足前缀和的子数组数量 + m[sum]++ + } + return cnt +} +``` + diff --git a/animation-simulation/前缀和/leetcode724寻找数组的中心索引.md b/animation-simulation/前缀和/leetcode724寻找数组的中心索引.md index 37ce953..80548e4 100644 --- a/animation-simulation/前缀和/leetcode724寻找数组的中心索引.md +++ b/animation-simulation/前缀和/leetcode724寻找数组的中心索引.md @@ -108,3 +108,23 @@ public: }; ``` +Go Code: + +```go +func pivotIndex(nums []int) int { + presum := 0 + for _, num := range nums { + presum += num + } + var leftsum int + for i, num := range nums { + // 比较左半和右半是否相同 + if presum - leftsum - num == leftsum { + return i + } + leftsum += num + } + return -1 +} +``` + diff --git a/animation-simulation/前缀和/leetcode974和可被K整除的子数组.md b/animation-simulation/前缀和/leetcode974和可被K整除的子数组.md index a6991ba..1cd105a 100644 --- a/animation-simulation/前缀和/leetcode974和可被K整除的子数组.md +++ b/animation-simulation/前缀和/leetcode974和可被K整除的子数组.md @@ -132,3 +132,21 @@ public: }; ``` +Go Code: + +```go +func subarraysDivByK(nums []int, k int) int { + m := make(map[int]int) + cnt := 0 + sum := 0 + m[0] = 1 + for _, num := range nums { + sum += num + key := (sum % k + k) % k + cnt += m[key] + m[key]++ + } + return cnt +} +``` +