Create Maximum Number

Posted keepshuatishuati

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Create Maximum Number相关的知识,希望对你有一定的参考价值。

 1 public class Solution {
 2     public int[] maxNumber(int[] nums1, int[] nums2, int k) {
 3         int[] result = new int[k];
 4         
 5         for (int i = Math.max(0, k - nums2.length); i <= k && i <= nums1.length; i++) {
 6             int[] candidate = merge(getMaxArray(nums1, i), getMaxArray(nums2, k - i), k);
 7             if (greater(candidate, 0, result, 0)) {
 8                 result = candidate;   
 9             }
10         } 
11         return result;
12     }
13     
14     
15     private int[] merge(int[] nums1, int[] nums2, int k) {
16         int[] result = new int[k];
17         for (int i = 0, j = 0, index = 0; index < k; index++) {
18             result[index] = greater(nums1, i, nums2, j) ? nums1[i++] : nums2[j++];
19         }
20         return result;
21     }
22     
23     private boolean greater(int[] nums1, int i, int[] nums2, int j) {
24         while (i < nums1.length && j < nums2.length && nums1[i] == nums2[j]) {
25             i++;
26             j++;
27         }
28         
29         return j == nums2.length || (i < nums1.length && nums1[i] > nums2[j]);
30     }
31     
32     private int[] getMaxArray(int[] nums, int k) {
33         int[] result = new int[k];
34         for (int i = 0, j = 0; i < nums.length; i++) {
35             while (nums.length - i + j > k && j > 0 && result[j-1] < nums[i]) {
36                 j--;
37             }
38             
39             if (j < k) {
40                 result[j++] = nums[i];
41             }
42         }
43         return result;
44     }
45 }

1. When divide k into two parts, it could be 0 for the any part. So i <= nums1.length.

以上是关于Create Maximum Number的主要内容,如果未能解决你的问题,请参考以下文章

Create Maximum Number

[LeetCode] Create Maximum Number

[LeetCode] Create Maximum Number

LeetCode-Create Maximum Number

Leetcode 321: Create Maximum Number

[LintCode] Create Maximum Number 创建最大数