Skip to content

Commit 4d8af49

Browse files
aQuaaQua
aQua
authored and
aQua
committed
442 finish
1 parent bf21d41 commit 4d8af49

File tree

3 files changed

+92
-0
lines changed

3 files changed

+92
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# [442. Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/)
2+
3+
## 题目
4+
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
5+
6+
Find all the elements that appear twice in this array.
7+
8+
Could you do it without extra space and in O(n) runtime?
9+
10+
Example:
11+
```
12+
Input:
13+
[4,3,2,7,8,2,3,1]
14+
Output:
15+
[2,3]
16+
```
17+
## 解题思路
18+
19+
见程序注释
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package Problem0442
2+
3+
import (
4+
"sort"
5+
)
6+
7+
func findDuplicates(a []int) []int {
8+
for i := 0; i < len(a); i++ {
9+
for a[i] != a[a[i]-1] {
10+
a[i], a[a[i]-1] = a[a[i]-1], a[i]
11+
}
12+
}
13+
14+
res := make([]int, 0, len(a))
15+
16+
for i, n := range a {
17+
if i != n-1 {
18+
res = append(res, n)
19+
}
20+
}
21+
22+
sort.Ints(res)
23+
24+
return res
25+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package Problem0442
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+
}
19+
20+
// ans 是答案
21+
type ans struct {
22+
one []int
23+
}
24+
25+
func Test_Problem0442(t *testing.T) {
26+
ast := assert.New(t)
27+
28+
qs := []question{
29+
30+
question{
31+
para{
32+
[]int{4, 3, 2, 7, 8, 2, 3, 1},
33+
},
34+
ans{
35+
[]int{2, 3},
36+
},
37+
},
38+
39+
// 如需多个测试,可以复制上方元素。
40+
}
41+
42+
for _, q := range qs {
43+
a, p := q.ans, q.para
44+
fmt.Printf("~~%v~~\n", p)
45+
46+
ast.Equal(a.one, findDuplicates(p.nums), "输入:%v", p)
47+
}
48+
}

0 commit comments

Comments
 (0)