Given two arrays of length m and n with digits 0-9representing 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.
Note: You should try to optimize your time and space complexity.
publicint[] largestK(int[] nums, int k) { int t = 0; int[] ans = newint[k]; for (int i=0; i<nums.length; i++) { int remain = nums.length - i - 1; while (remain + (t+1) > k && t > 0 && nums[i] > ans[t-1]) { t --; } if (t < k) ans[t++] = nums[i]; } return ans; }
publicint[] merge(int[] nums1, int[] nums2) { int i=0; int j=0; int t=0; int [] result = newint[nums1.length + nums2.length]; while (i < nums1.length || j < nums2.length) { if (i >= nums1.length) { result[t++] = nums2[j++]; } elseif (j >= nums2.length) { result[t++] = nums1[i++]; } elseif (nums1[i] < nums2[j]) { result[t++] = nums2[j++]; } else { result[t++] = nums1[i++]; } } return result; }