-
Notifications
You must be signed in to change notification settings - Fork 0
/
question75.go
56 lines (46 loc) · 1.01 KB
/
question75.go
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
package chapter12
import (
"math"
"github.com/syhily/code-interviews/common"
)
func countingSort(numbers ...int) []int {
max, min := math.MinInt, math.MaxInt
for _, number := range numbers {
max = common.MaxNumber(max, number)
min = common.MinNumber(min, number)
}
counts := make([]int, max-min+1)
for _, number := range numbers {
counts[number-min]++
}
res := make([]int, 0, len(numbers))
for d, count := range counts {
for i := 0; i < count; i++ {
res = append(res, d+min)
}
}
return res
}
func sortByGivenIndex(arr1, arr2 []int) []int {
// Count the occur times of items in arr1.
counts := make([]int, 1001)
for _, i := range arr1 {
counts[i]++
}
// Get the elements from arr2 one by one.
res := make([]int, 0, len(arr1))
for _, i := range arr2 {
count := counts[i]
counts[i] = 0
for j := 0; j < count; j++ {
res = append(res, i)
}
}
// Append the remaining numbers.
for i, count := range counts {
for j := 0; j < count; j++ {
res = append(res, i)
}
}
return res
}