Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 11 additions & 14 deletions leetcode/201-300/0238.Product-of-Array-Except-Self/README.md
Original file line number Diff line number Diff line change
@@ -1,28 +1,25 @@
# [238.Product of Array Except Self][title]

> [!WARNING|style:flat]
> This question is temporarily unanswered if you have good ideas. Welcome to [Create Pull Request PR](https://github.com/kylesliu/awesome-golang-algorithm)

## Description
Given an integer array `nums`, return an array `answer` such that `answer[i]` is equal to the product of all the elements of `nums` except `nums[i]`.

The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.

You must write an algorithm that runs in `O(n)` time and without using the division operation.

**Example 1:**

```
Input: a = "11", b = "1"
Output: "100"
Input: nums = [1,2,3,4]
Output: [24,12,8,6]
```

## 题意
> ...
**Example 2:**

## 题解

### 思路1
> ...
Product of Array Except Self
```go
```

Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]
```

## 结语

Expand Down
23 changes: 21 additions & 2 deletions leetcode/201-300/0238.Product-of-Array-Except-Self/Solution.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,24 @@
package Solution

func Solution(x bool) bool {
return x
func Solution(nums []int) []int {
length := len(nums)
r := make([]int, length)
if length == 0 || length == 1 {
return r
}

r[0] = nums[0]
for i := 1; i < length-1; i++ {
r[i] = r[i-1] * nums[i]
}
r[length-1] = r[length-2]

rightProduct := nums[length-1]
for idx := length - 2; idx > 0; idx-- {
r[idx] = r[idx-1] * rightProduct
rightProduct *= nums[idx]
}
r[0] = rightProduct

return r
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,13 @@ func TestSolution(t *testing.T) {
// 测试用例
cases := []struct {
name string
inputs bool
expect bool
inputs []int
expect []int
}{
{"TestCase", true, true},
{"TestCase", true, true},
{"TestCase", false, false},
{"TestCase1", []int{1, 2, 3, 4}, []int{24, 12, 8, 6}},
{"TestCase2", []int{-1, 1, 0, -3, 3}, []int{0, 0, 9, 0, 0}},
{"TestCase3", []int{2, 3, 5, 0}, []int{0, 0, 0, 30}},
{"TestCase4", []int{1, 1, 1}, []int{1, 1, 1}},
}

// 开始测试
Expand Down