【題目描述】
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
Given nums1 =?[3, 4, 6, 5], nums2 =?[9, 1, 2, 5, 8, 3], k =?5
return?[9, 8, 6, 5, 3]
Given nums1 =?[6, 7], nums2 =?[6, 0, 4], k =?5
return?[6, 7, 6, 0, 4]
Given nums1 =?[3, 9], nums2 =?[8, 9], k =?3
return?[9, 8, 9]
給出兩個長度分別是m和n的數組來表示兩個大整數,數組的每個元素都是數字0-9。從這兩個數組當中選出k個數字來創建一個最大數,其中k滿足k <= m + n。選出來的數字在創建的最大數里面的位置必須和在原數組內的相對位置一致。返回k個數的數組。你應該盡可能的去優化算法的時間復雜度和空間復雜度。
樣例
給出 nums1 =?[3, 4, 6, 5], nums2 =?[9, 1, 2, 5, 8, 3], k =?5
返回?[9, 8, 6, 5, 3]
給出 nums1 =?[6, 7], nums2 =?[6, 0, 4], k =?5
返回?[6, 7, 6, 0, 4]
給出 nums1 =?[3, 9], nums2 =?[8, 9], k =?3
返回?[9, 8, 9]
【題目鏈接】
www.lintcode.com/en/problem/create-maximum-number/
【題目解析】
從nums1中選擇i個數,從nums2中選擇k-i個數,使得合成的數最大。
分成兩個子問題:
1. 如何從一個數組中選擇i個數,使這i個數表示的數值是所有候選中最大的
? ? 比如[9, 1, 2, 5, 8, 3] i = 2; 如何得到 [9,8]
2. 如何合并兩個數組使得形成最大的值
? ? ?比如[9, 8, 3] [6,5]; 如何得到[9,8,6,5,3]
【參考答案】