-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy path164. Maximum Gap.go
83 lines (79 loc) · 1.53 KB
/
164. Maximum Gap.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package leetcode
// 解法一 快排
func maximumGap(nums []int) int {
if len(nums) < 2 {
return 0
}
quickSort164(nums, 0, len(nums)-1)
res := 0
for i := 0; i < len(nums)-1; i++ {
if (nums[i+1] - nums[i]) > res {
res = nums[i+1] - nums[i]
}
}
return res
}
func partition164(a []int, lo, hi int) int {
pivot := a[hi]
i := lo - 1
for j := lo; j < hi; j++ {
if a[j] < pivot {
i++
a[j], a[i] = a[i], a[j]
}
}
a[i+1], a[hi] = a[hi], a[i+1]
return i + 1
}
func quickSort164(a []int, lo, hi int) {
if lo >= hi {
return
}
p := partition164(a, lo, hi)
quickSort164(a, lo, p-1)
quickSort164(a, p+1, hi)
}
// 解法二 基数排序
func maximumGap1(nums []int) int {
if nums == nil || len(nums) < 2 {
return 0
}
// m is the maximal number in nums
m := nums[0]
for i := 1; i < len(nums); i++ {
m = max(m, nums[i])
}
exp := 1 // 1, 10, 100, 1000 ...
R := 10 // 10 digits
aux := make([]int, len(nums))
for (m / exp) > 0 { // Go through all digits from LSB to MSB
count := make([]int, R)
for i := 0; i < len(nums); i++ {
count[(nums[i]/exp)%10]++
}
for i := 1; i < len(count); i++ {
count[i] += count[i-1]
}
for i := len(nums) - 1; i >= 0; i-- {
tmp := count[(nums[i]/exp)%10]
tmp--
aux[tmp] = nums[i]
count[(nums[i]/exp)%10] = tmp
}
for i := 0; i < len(nums); i++ {
nums[i] = aux[i]
}
exp *= 10
}
maxValue := 0
for i := 1; i < len(aux); i++ {
maxValue = max(maxValue, aux[i]-aux[i-1])
}
return maxValue
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}