原题链接在这里:https://leetcode.com/problems/create-maximum-number/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]
题解:
从nums1中挑出i个数, 从nums2中挑出k-i个数合并组成最大的数.
那么就可以分成两个小问题了.
第一个是如何从一个数组中挑出i个数, 使表示的数字最大.
第二个是完全合并两个数组使表达数字最大.
先看第一个问题, 挑出i个数使合成的数字最大. 利用stack, 若是剩下的数字个数还足够, 看stack顶部若是比当前数字小可以替换掉. 由于stack的size是固定的, 可以用array表示.
第二个问题是两个数组nums1, nums2, 完全合并成新的数组size为k = num1.length+nums2.length如何做到最大. 挑选nums1, nums2当前位置较大的数. 但若是相等的就要看后面的位.
最后挨个试i, 也就是从nums1中挑出数字的个数. 看组成的candidate是否更大, 维护res.
Note: i range, i >= Math.max(0, k - nums2.length). When nums2 is short, nums1 need to at least extract some digits.
i <= k, when nums1 is too long, extract number must be small or equal to k.
Time Complexity: O((m+n)^3). m = nums1.length, n = nums2.length. 两个maxArray共用时O(k). merge用了i*(k-i). i从小到大试了个遍, 所以共用时O(k^2). k最大是m+n.
Space Complexity: O(m+n).
AC Java:
1 class Solution { 2 public int[] maxNumber(int[] nums1, int[] nums2, int k) { 3 int [] res = new int[k]; 4 for(int i = Math.max(0, k-nums2.length); i<=nums1.length&&i<=k; i++){ 5 int [] candidate = merge(maxArray(nums1, i), maxArray(nums2, k-i), k); 6 if(greater(candidate, 0, res, 0)){ 7 res = candidate; 8 } 9 } 10 return res; 11 } 12 13 private int [] merge(int [] nums1, int [] nums2, int k){ 14 int [] res = new int[k]; 15 for(int i = 0, j = 0, r = 0; r<k; r++){ 16 res[r] = greater(nums1, i, nums2, j) ? nums1[i++] : nums2[j++]; 17 } 18 return res; 19 } 20 21 private boolean greater(int [] nums1, int i, int [] nums2, int j){ 22 while(i<nums1.length && j<nums2.length && nums1[i]==nums2[j]){ 23 i++; 24 j++; 25 } 26 return j==nums2.length || (i<nums1.length && nums1[i]>nums2[j]); 27 } 28 29 private int [] maxArray(int [] nums, int k){ 30 int len = nums.length; 31 int [] res = new int[k]; 32 for(int i = 0, po = 0; i<len; i++){ 33 while(len-i>k-po && po>0 && res[po-1]<nums[i]){ 34 po--; 35 } 36 if(po < k){ 37 res[po++] = nums[i]; 38 } 39 } 40 return res; 41 } 42 }