Files
leetcode/top-100-liked/16_test.go
T
2026-06-01 03:33:34 +10:00

58 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package top100liked
import (
"fmt"
"testing"
)
// https://leetcode.cn/problems/product-of-array-except-self/?envType=study-plan-v2&envId=top-100-liked
// func productExceptSelf(nums []int) []int {
// left := make([]int, len(nums))
// right := make([]int, len(nums))
// left[0] = nums[0]
// right[len(nums)-1] = nums[len(nums)-1]
// for i := 1; i < len(nums); i++ {
// left[i] = left[i-1] * nums[i]
// }
// for i := len(nums) - 2; i >= 0; i-- {
// right[i] = right[i+1] * nums[i]
// }
// res := []int{}
// for i := range nums {
// if i == 0 {
// res = append(res, right[1])
// } else if i == len(nums)-1 {
// res = append(res, left[len(nums)-2])
// } else {
// res = append(res, left[i-1]*right[i+1])
// }
// }
// return res
// }
func productExceptSelf(nums []int) []int {
n := len(nums)
answer := make([]int, n)
// 第一遍:计算左边乘积,存入 answer
answer[0] = 1
for i := 1; i < n; i++ {
answer[i] = answer[i-1] * nums[i-1]
}
// 第二遍:从右向左,用 R 维护右边乘积
R := 1
for i := n - 1; i >= 0; i-- {
answer[i] = answer[i] * R // 左边积 × 右边积
R = R * nums[i] // 更新右边积
}
return answer
}
func TestS16(t *testing.T) {
fmt.Printf("%+v", productExceptSelf([]int{1, 2, 3, 4}))
fmt.Printf("%+v", productExceptSelf([]int{-1, 1, 0, -3, 3}))
}