LeetCode: 321. Create Maximum Number
题目描述
Given two arrays of length m and n with digits 0-9 representing two numbers. Create the maximum number of length k <= m + n from digits of the two. The relative order of the digits from the same array must be preserved. Return an array of the k digits.
Note: You should try to optimize your time and space complexity.
Example 1:
Input:
nums1 = [3, 4, 6, 5]
nums2 = [9, 1, 2, 5, 8, 3]
k = 5
Output:
[9, 8, 6, 5, 3]
Example 2:
Input:
nums1 = [6, 7]
nums2 = [6, 0, 4]
k = 5
Output:
[6, 7, 6, 0, 4]
Example 3:
Input:
nums1 = [3, 9]
nums2 = [8, 9]
k = 3
Output:
[9, 8, 9]
解题思路
组成最终数字的 k 个数字拆分到两个数组中,该问题转化为:
- 数组 nums 抽出 k 个数按照原序组成的最大数字
- 两个数组按照原序拼成最大的数字
AC 代码
// 数组 nums 抽出 k 个数按照原序组成的最大数字
func maxNumberFrom(nums []int, k int) []int {
if k == 0 || len(nums) == 0 || len(nums) < k {
return nil
}
maxIdx := 0
for i := 1; i < len(nums) - k + 1; i++ {
if nums[i] > nums[maxIdx] {
maxIdx = i
}
}
next := maxNumberFrom(nums[maxIdx+1:], k-1)
maxn := []int{ nums[maxIdx] }
maxn = append(maxn, next...)
return maxn
}
// 将 num1, num2 拼成最大的数字
func merge(nums1 []int, nums2 []int) []int {
var mergeNum []int
for i, j := 0, 0; i < len(nums1) || j < len(nums2); {
if compare(nums1[i:], nums2[j:]) >= 0 {
mergeNum = append(mergeNum, nums1[i])
i++
} else {
mergeNum = append(mergeNum, nums2[j])
j++
}
}
return mergeNum
}
func compare(nums1, nums2 []int) (ans int) {
for i := 0; i < len(nums1) && i < len(nums2); i++ {
if nums1[i] > nums2[i] {
return 1
} else if nums2[i] > nums1[i] {
return -1
}
}
if len(nums1) > len(nums2) {
return 1
} else if len(nums1) < len(nums2) {
return -1
} else {
return 0
}
}
// 获取两个数组中组成最大数字的那个数组
func max(nums1, nums2 []int) []int {
if compare(nums1, nums2) >= 0 {
return nums1
} else {
return nums2
}
}
func maxNumber(nums1 []int, nums2 []int, k int) []int {
var ans []int
for len1 := 0; len1 <= k && len1 <= len(nums1); len1++ {
len2 := k - len1
if len2 > len(nums2) {
continue
}
max1 := maxNumberFrom(nums1, len1)
max2 := maxNumberFrom(nums2, len2)
ans = max(ans, merge(max1, max2))
}
return ans
}