# Leetcode题解 321. Create Maximum Number

112人阅读 评论(0)

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. 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]

1、栈空
2、剩余的数组不足以填满栈至 k

 public static int[] maxArray(int[] nums, int k) {
int n = nums.length;
int[] result = new int[k];
for (int i = 0, j = 0; i < n; i++) {
while (n - i + j > k && j > 0 && result[j - 1] < nums[i]) j--;
if (j < k) result[j++] = nums[i];
}
return result;
}

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

public static int[] merge(int[] num1, int[] num2, int k) {
int[] res = new int[k];
int i = 0;
int j = 0;
for (int l = 0; l < k; l++) {
if (greater(num1,num2,i,j)) {
res[l] = num1[i++];
} else {
res[l] = num2[j++];
}
}
return res;
}
public static boolean greater(int[] a,int[]b,int i,int j){
while(i<a.length&&j<b.length&&a[i]==b[j]){
i++;j++;
}
return j == b.length|| (i<a.length&& a[i] > b[j]);
}

public int[] maxNumber(int[] nums1, int[] nums2, int k) {
if(nums1==null||nums1.length==0){
return maxArray(nums2,k);
}else if(nums2==null||nums2.length==0){
return maxArray(nums1,k);
}
int[] res = new int[k];
int len1=nums1.length;
int len2=nums2.length;
for (int i = Math.max(0,k-len2); i < k && i<=len1; i++) {
int[] t1 = maxArray(nums1, i);
int[] t2 = maxArray(nums2, k-i);
int[] temp = merge(t1, t2, k);
if (greater(temp, res, 0, 0)) res = temp;
}
return res;
}
0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：34409次
• 积分：1809
• 等级：
• 排名：千里之外
• 原创：153篇
• 转载：11篇
• 译文：0篇
• 评论：0条
阅读排行