Skip to content

Commit

Permalink
Add solution and test-cases for problem 1685
Browse files Browse the repository at this point in the history
  • Loading branch information
0xff-dev committed Nov 25, 2023
1 parent 78cc0c7 commit 932e6dc
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 23 deletions.
Original file line number Diff line number Diff line change
@@ -1,28 +1,29 @@
# [1685.Sum of Absolute Differences in a Sorted Array][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
You are given an integer array `nums` sorted in **non-decreasing** order.

Build and return an integer array `result` with the same length as `nums` such that `result[i]` is equal to the **summation of absolute differences** between `nums[i]` and all the other elements in the array.

In other words, `result[i]` is equal to `sum(|nums[i]-nums[j]|)` where `0 <= j < nums.lengt`h and `j != i` (**0-indexed**).

**Example 1:**

```
Input: a = "11", b = "1"
Output: "100"
Input: nums = [2,3,5]
Output: [4,3,5]
Explanation: Assuming the arrays are 0-indexed, then
result[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,
result[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,
result[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.
```

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

## 题解

### 思路1
> ...
Sum of Absolute Differences in a Sorted Array
```go
```

Input: nums = [1,4,6,8,10]
Output: [24,15,13,15,21]
```

## 结语

Expand Down
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 {
l := len(nums)
sum := make([]int, l)
sum[0] = nums[0]
for i := 1; i < l; i++ {
sum[i] = sum[i-1] + nums[i]
}
result := make([]int, len(nums))
for i := 0; i < l; i++ {
left, right := 0, 0
if i > 0 {
s := sum[i-1]
left = i*nums[i] - s
}
if i < l-1 {
s := sum[l-1] - sum[i]
right = s - (l-1-i)*nums[i]
}
result[i] = left + right
}
return result
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,11 @@ 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{2, 3, 5}, []int{4, 3, 5}},
{"TestCase2", []int{1, 4, 6, 8, 10}, []int{24, 15, 13, 15, 21}},
}

// 开始测试
Expand All @@ -30,10 +29,10 @@ func TestSolution(t *testing.T) {
}
}

// 压力测试
// 压力测试
func BenchmarkSolution(b *testing.B) {
}

// 使用案列
// 使用案列
func ExampleSolution() {
}

0 comments on commit 932e6dc

Please sign in to comment.