321. Create Maximum Number - jiejackyzhang/leetcode-note GitHub Wiki

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. create maximum number from one array of length k
  2. create maximum number from two arrays using all their numbers

如此我们可以把问题转换为: nums1产生长度为i的max number,nums2产生长度为k-i的max number,然后把这两个结果merge为最终结果。 最后在所有可能性中求最大值。

在merge的时候需注意有相同的情形存在,需要比较出确定的大小。比如[6,7]和[6],当相同时,不能任意添加,需要判断出nums1 > nums2,这样才能merge成[6,7,6],否则会导致[6,6,7]。

public class Solution {
    public int[] maxNumber(int[] nums1, int[] nums2, int k) {
        int m = nums1.length;
        int n = nums2.length;
        int[] res = new int[k];
        if(m+n < k) return res;
        for(int i = Math.max(0, k-n); i <= m && i <= k; i++) {
            int[] candidate = merge(maxArray(nums1, i), maxArray(nums2, k-i));
            if(greater(candidate, 0, res, 0)) res = candidate;
        }
        return res;
    }
    
    private int[] maxArray(int[] nums, int k) {
        int n = nums.length;
        int[] res = new int[k];
        for(int i = 0, j = 0; i < n; i++) {
            // 若剩下的数字够用,则可以替换已用的数字
            while(n-i+j > k && j > 0 && res[j-1] < nums[i]) j--;
            if(j < k) res[j++] = nums[i];
        }
        return res;
    }

    private int[] merge(int[] nums1, int[] nums2) {
        int k = nums1.length + nums2.length;
        int[] res = new int[k];
        for(int i = 0, j = 0, r = 0; r < k; r++) {
            res[r] = greater(nums1, i, nums2, j) ? nums1[i++] : nums2[j++];
        }
        return res;
    }

    private boolean greater(int[] nums1, int i, int[] nums2, int j) {
        while(i < nums1.length && j < nums2.length && nums1[i] == nums2[j]) {
            i++;
            j++;
        }
        // 前面数字都相同时,长的那个更大,因此判断j == nums2.length
        // 若相等,则说明nums2已到结尾,而且所有数字均与nums1前n个相同,则nums1更大,返回true
        return j == nums2.length || (i < nums1.length && nums1[i] > nums2[j]);
    }
}