Modify solution 0164

This commit is contained in:
YDZ
2021-01-02 01:14:29 +08:00
parent 3e2d511c6b
commit fb72c855ee
3 changed files with 19 additions and 28 deletions

View File

@ -1,12 +1,11 @@
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 {
@ -37,52 +36,42 @@ func quickSort164(a []int, lo, hi int) {
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
}

View File

@ -49,6 +49,11 @@ func Test_Problem164(t *testing.T) {
para164{[]int{2, 435, 214, 64321, 643, 7234, 7, 436523, 7856, 8}},
ans164{372202},
},
{
para164{[]int{1, 10000000}},
ans164{9999999},
},
}
fmt.Printf("------------------------Leetcode Problem 164------------------------\n")

View File

@ -51,13 +51,12 @@ Explanation: The array contains less than 2 elements, therefore return 0.
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 {
@ -88,53 +87,51 @@ func quickSort164(a []int, lo, hi int) {
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
}
```