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

Commit ddc4480

Browse files
aQuaaQua
aQua
authored and
aQua
committed
189 accepted
329ms, fastest is 123ms
1 parent 1ad59a0 commit ddc4480

File tree

3 files changed

+82
-0
lines changed

3 files changed

+82
-0
lines changed
+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# [189. Rotate Array](https://leetcode.com/problems/rotate-array/)
2+
3+
## 题目
4+
5+
Rotate an array of n elements to the right by k steps.
6+
For example, with n = 7 and k = 3, the array `[1,2,3,4,5,6,7]` is rotated to `[5,6,7,1,2,3,4]`.
7+
8+
Note:
9+
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
10+
11+
12+
[show hint]
13+
Hint:
14+
Could you do it in-place with O(1) extra space?
15+
16+
17+
Related problem: [Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/)
18+
19+
## 解题思路
20+
21+
22+
见程序注释
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package Problem0189
2+
3+
func rotate(nums []int, k int) {
4+
for i := 0; i < k; i++ {
5+
temp := nums[len(nums)-1]
6+
for j := len(nums) - 1; j > 0; j-- {
7+
nums[j] = nums[j-1]
8+
}
9+
nums[0] = temp
10+
}
11+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package Problem0189
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
type question struct {
11+
para
12+
ans
13+
}
14+
15+
// para 是参数
16+
type para struct {
17+
nums []int
18+
k int
19+
}
20+
21+
// ans 是答案
22+
type ans struct {
23+
one []int
24+
}
25+
26+
func Test_Problem0189(t *testing.T) {
27+
ast := assert.New(t)
28+
29+
qs := []question{
30+
31+
question{
32+
para{
33+
[]int{1, 2, 3, 4, 5, 6, 7}, 3,
34+
},
35+
ans{
36+
[]int{5, 6, 7, 1, 2, 3, 4},
37+
},
38+
},
39+
40+
// 如需多个测试,可以复制上方元素。
41+
}
42+
43+
for _, q := range qs {
44+
a, p := q.ans, q.para
45+
fmt.Printf("~~%v~~\n", p)
46+
rotate(p.nums, p.k)
47+
ast.Equal(a.one, p.nums, "输入:%v", p)
48+
}
49+
}

0 commit comments

Comments
 (0)