Create Maximum Number

时间:2022-10-03 21:39:24

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

Given nums1 = [3, 4, 6, 5], nums2 = [9, 1, 2, 5, 8, 3], k = 5
return [9, 8, 6, 5, 3]

Given nums1 = [6, 7], nums2 = [6, 0, 4], k = 5
return [6, 7, 6, 0, 4]

Given nums1 = [3, 9], nums2 = [8, 9], k = 3
return [9, 8, 9]

这道题是参考网上的解法,是道难题。。注意比较两个字符数串的大小 而不是当前字符数字的大小 (参考反例 60 604)
 
 public class Solution {
/**
* @param nums1 an integer array of length m with digits 0-9
* @param nums2 an integer array of length n with digits 0-9
* @param k an integer and k <= m + n
* @return an integer array
*/
public int[] maxNumber(int[] nums1, int[] nums2, int k) {
// Write your code here
int len1 = nums1.length;
int len2 = nums2.length;
int[] res = new int[k];
for(int i = Math.max(0, k-len2); i<=k&&i<=len1;i++){
int[] temp = merge(maxArray(nums1, i), maxArray(nums2, k-i), k);
if(isGreater(temp, 0, res, 0)){
res = temp;
}
}
return res;
} private int[] maxArray(int[] nums, int len){
int[] res = new int[len];
int j = 0;
int n = nums.length;
for(int i=0; i<n;i++){
while(j>0&&j+n-i>len&&res[j-1]<nums[i]){
j--;
}
if(j<len){
res[j] = nums[i];
j++;
}
}
return res;
} private int[] merge(int[] a, int[] b, int len){
int[] res = new int[len];
int len1 = a.length;
int len2 = b.length;
if(len1==0) return b;
if(len2==0) return a;
int i=0; int j=0;
int index=0;
while(i<len1||j<len2){
if(isGreater(a, i, b, j)){
res[index++]=a[i++];
}else{
res[index++]=b[j++];
}
}
while(i<len1){
res[index++]=a[i++];
}
while(j<len2){
res[index++]=b[j++];
}
return res;
} private boolean isGreater(int[] a, int posA, int[] b, int posB){
int len1 = a.length;
int len2 = b.length;
int i=posA; int j=posB;
while(i<len1&&j<len2&&a[i]==b[j]){
i++;
j++;
} if(i==len1) return false;
if(j==len2) return true;
return a[i]>b[j];
}
}