-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray_duplicate_numbers.go
More file actions
57 lines (48 loc) · 1.47 KB
/
array_duplicate_numbers.go
File metadata and controls
57 lines (48 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package main
// GetDuplicateNumbers aims to find all duplicated numbers in a slice of
// numbers. I have assumed the order is not important.
// Solution O(n)
// This makes use of Go's named return values.
func GetDuplicateNumbers(numbers []int) (dupes []int) {
// keep track of numbers in the array
count := make(map[int]struct{})
for _, n := range numbers {
if _, ok := count[n]; ok {
// Number is in map - it is repeated.
dupes = append(dupes, n)
} else {
// First occurrence of the number, store in set.
count[n] = struct{}{}
}
}
return dupes
}
// GetDuplicateNumbersInOrder aims to find all duplicated numbers in a slice of
// numbers, in the order they originally appeared in the array
// Solution O(n)
// This makes use of Go's named return values.
func GetDuplicateNumbersInOrder(numbers []int) (dupes []int) {
// keep track of numbers in the array
count := make(map[int]struct{})
// Another "Set" to store the duplicates.
dupeMap := make(map[int]struct{})
for _, n := range numbers {
if _, ok := count[n]; ok {
// Number is in map - it is repeated.
dupeMap[n] = struct{}{}
} else {
// First occurrence of the number, store in set.
count[n] = struct{}{}
}
}
// Go through the numbers one more time to get the dupes in order
for _, n := range numbers {
if _, ok := dupeMap[n]; ok {
// Remove from the map so we don't get dupes in the actual
// return slice.
delete(dupeMap, n)
dupes = append(dupes, n)
}
}
return dupes
}