Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit ca72dc3

Browse files
aQuaaQua
aQua
authored and
aQua
committed
462 added
1 parent 935012f commit ca72dc3

File tree

3 files changed

+72
-0
lines changed

3 files changed

+72
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# [462. Minimum Moves to Equal Array Elements II](https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/)
2+
3+
## 题目
4+
5+
Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1.
6+
7+
You may assume the array's length is at most 10,000.
8+
9+
Example:
10+
11+
```text
12+
Input:
13+
[1,2,3]
14+
15+
Output:
16+
2
17+
18+
Explanation:
19+
Only two moves are needed (remember each move increments or decrements one element):
20+
21+
[1,2,3] => [2,2,3] => [2,2,2]
22+
```
23+
24+
## 解题思路
25+
26+
见程序注释
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package Problem0462
2+
3+
func minMoves2(nums []int) int {
4+
res := 2
5+
6+
return res
7+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package Problem0462
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
// tcs is testcase slice
11+
var tcs = []struct {
12+
nums []int
13+
ans int
14+
}{
15+
16+
{
17+
[]int{1, 2, 3},
18+
2,
19+
},
20+
21+
// 可以有多个 testcase
22+
}
23+
24+
func Test_minMoves2(t *testing.T) {
25+
ast := assert.New(t)
26+
27+
for _, tc := range tcs {
28+
fmt.Printf("~~%v~~\n", tc)
29+
ast.Equal(tc.ans, minMoves2(tc.nums), "输入:%v", tc)
30+
}
31+
}
32+
33+
func Benchmark_minMoves2(b *testing.B) {
34+
for i := 0; i < b.N; i++ {
35+
for _, tc := range tcs {
36+
minMoves2(tc.nums)
37+
}
38+
}
39+
}

0 commit comments

Comments
 (0)