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]
这一题挺难的,我用的最慢的方法~将k分成两部分,首先从第一个数组里取i个可以组成最大i位数的数,然后从第二个数组里取k-i个可以组成最大数的数,然后组合起来成一个最大的数,i从最小到最大遍历一次,从而求得最大的数。当然很慢了,我看tags里是用动态规划或贪婪算法的。不过我去大家的博客里看了看,都是这种方法~那就酱紫吧~
import java.math.BigInteger; public class Solution { public int[] maxNumber(int[] nums1, int[] nums2, int k) { int len1 = nums1.length; int len2 = nums2.length; int i = k; BigInteger max = BigInteger.ZERO; if(k>len1){ i = len1; } for(; i >= 0 && k-i<=len2; i--){ int[] num1 = calmaxnum(nums1,i); int[] num2 = calmaxnum(nums2,k-i); BigInteger maxnum = totalmaxnum(num1,num2); if(maxnum.compareTo(max)>0){ max = maxnum; } } int[] ans = convertToArray(max); return ans; } int[] calmaxnum(int[] num,int k){ int[] ans = new int[k]; int len = num.length; int index = 0; for(int i = 0; i < k; i++){ int[] ans2= findmaxnum(num,index,len-k+i+1); ans[i] = ans2[0]; index = ans2[1]+1; } return ans; } int[] findmaxnum(int[] num,int left,int right){ int max = num[left]; //int max = 0; int index = left; for(int i = left;i<right;i++){ if(num[i]>max){ max = num[i]; index = i; } } int[] ans = {max , index}; return ans; } BigInteger totalmaxnum(int[] num1, int[] num2){ int len1 = num1.length; int len2 = num2.length; int index1 = 0; int index2 = 0; String str = ""; for(int i = 0; i<len1+len2; i++){ if(index1>=len1){ str += num2[index2++]; }else if(index2 >= len2){ str += num1[index1++]; }else if(num1[index1]>num2[index2]){ str += num1[index1++]; }else if(num1[index1]<num2[index2]){ str += num2[index2++]; }else{ int tempindex1 = index1; int tempindex2 = index2; while(true){ tempindex1++; tempindex2++; if(tempindex1 >=len1){ str += num2[index2++]; break; }else if(tempindex2 >= len2){ str += num1[index1++]; break; }else if(num1[tempindex1]>num2[tempindex2]){ str += num1[index1++]; break; }else if(num1[tempindex1]<num2[tempindex2]){ str += num2[index2++]; break; } } } } BigInteger ans = new BigInteger(str); return ans; } int[] convertToArray(BigInteger max){ String str = ""+max; int len = str.length(); int[] ans = new int[len]; for(int i = len-1; i>=0; i--){ ans[i] = (max.remainder(BigInteger.valueOf(10))).intValue(); max = max.divide(BigInteger.valueOf(10)); } return ans; } }