leetcode321.Create Maximum Number
题目要求
1 | 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. |
思路和代码
首先采用分治法的思路,我们知道这K个数字中,必然有i个数组来自nums1,而剩下的k-i个数字必然来自nums2。
那么问题变成从nums1中获取i个数,这i个数构成的数字最大,且这i个数字的相对位置不变。
再从nums2中获取k-i个数,这k-i个数构成的数字最大,且这k-i个数字的相对位置不变。
那么我们如何将这两个结果合并起来获得我们最终的结果呢?
这里很像归并算法的merge过程,我们从两个数组的开头获取最大的值加进来呗。
那如果出现相同的值怎么办?那么继续比较,直到遇到第一个不相同的数字,然后选择数字较大的那个数组。
1 | public int[] maxNumber(int[] nums1, int[] nums2, int k) { |