Description:
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. You should try to optimize your time and space complexity.
Example 1:
nums1 = [3, 4, 6, 5]
nums2 = [9, 1, 2, 5, 8, 3]
k = 5
return [9, 8, 6, 5, 3]
Example 2:
nums1 = [6, 7]
nums2 = [6, 0, 4]
k = 5
return [6, 7, 6, 0, 4]
Example 3:
nums1 = [3, 9]
nums2 = [8, 9]
k = 3
return [9, 8, 9]
Solution:
这道题目一开始被hard吓到了,但实际上也就编码程度复杂点。
首先确定nums1取几个数字,nums2取几个数字,因为所取的数字数量确定,所以贪心就可以找到。
然后再将二者merge。
<span style="font-size:18px;">public class Solution {
public int[] maxNumber(int[] nums1, int[] nums2, int k) {
int[] ans = new int[k];
for (int lena = 0; lena <= k && lena <= nums1.length; lena++) {
int lenb = k - lena;
if (lenb > nums2.length)
continue;
int neo[] = merge(createArray(nums1, lena),
createArray(nums2, lenb));
if (isGreater(ans, 0, neo, 0))
continue;
ans = neo;
}
return ans;
}
public int[] createArray(int[] num, int k) {
int neo[] = new int[k];
int start = 0, max, max_index;
for (int i = 0; i < k; i++) {
max = num[start];
max_index = start;
for (int j = start; j <= num.length - k + i; j++)
if (num[j] > max) {
max = num[j];
max_index = j;
}
start = max_index + 1;
neo[i] = max;
}
return neo;
}
public int[] merge(int[] a, int[] b) {
int la = a.length;
int lb = b.length;
int k = la + lb;
int[] neo = new int[k];
int tot = 0;
int i = 0, j = 0;
for (; i < la && j < lb;) {
if (a[i] > b[j])
neo[tot++] = a[i++];
else if (a[i] < b[j])
neo[tot++] = b[j++];
else {
if (isGreater(a, i, b, j))
neo[tot++] = a[i++];
else
neo[tot++] = b[j++];
}
}
while (i < a.length)
neo[tot++] = a[i++];
while (j < b.length)
neo[tot++] = b[j++];
return neo;
}
public boolean isGreater(int[] a, int startA, int[] b, int startB) {
for (; startA < a.length && startB < b.length; startA++, startB++) {
if (a[startA] > b[startB])
return true;
if (a[startA] < b[startB])
return false;
}
return startA != a.length;
}
}</span>