Leetcode 321: Create Maximum Number
Posted Keep walking
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 321: Create Maximum Number相关的知识,希望对你有一定的参考价值。
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 public class Solution { 2 public int[] MaxNumber(int[] nums1, int[] nums2, int k) { 3 var res = DFS(nums1, nums2, k, 0, 0, new List<int>()); 4 return res.ToArray(); 5 } 6 7 private IList<int> DFS(int[] nums1, int[] nums2, int k, int start1, int start2, IList<int> cur) 8 { 9 if (cur.Count >= k) 10 { 11 return cur; 12 } 13 14 int pos1 = start1; 15 16 for (int i = start1; i < nums1.Length; i++) 17 { 18 // break if don‘t have enough digits 19 if (nums1.Length - i + nums2.Length - start2 < k - cur.Count) 20 { 21 break; 22 } 23 24 if (nums1[i] > nums1[pos1]) 25 { 26 pos1 = i; 27 } 28 } 29 30 int pos2 = start2; 31 32 for (int i = start2; i < nums2.Length; i++) 33 { 34 // break if don‘t have enough digits 35 if (nums2.Length - i + nums1.Length - start1 < k - cur.Count) 36 { 37 break; 38 } 39 40 if (nums2[i] > nums2[pos2]) 41 { 42 pos2 = i; 43 } 44 } 45 46 if (start1 >= nums1.Length) 47 { 48 cur.Add(nums2[pos2]); 49 50 return DFS(nums1, nums2, k, start1, pos2 + 1, cur); 51 } 52 else if (start2 >= nums2.Length) 53 { 54 cur.Add(nums1[pos1]); 55 56 return DFS(nums1, nums2, k, pos1 + 1, start2, cur); 57 } 58 else if (nums1[pos1] > nums2[pos2]) 59 { 60 cur.Add(nums1[pos1]); 61 62 return DFS(nums1, nums2, k, pos1 + 1, start2, cur); 63 } 64 else if (nums1[pos1] < nums2[pos2]) 65 { 66 cur.Add(nums2[pos2]); 67 68 return DFS(nums1, nums2, k, start1, pos2 + 1, cur); 69 } 70 else 71 { 72 var cur1 = new List<int>(cur); 73 cur.Add(nums1[pos1]); 74 var r1 = DFS(nums1, nums2, k, pos1 + 1, start2, cur); 75 76 cur1.Add(nums2[pos2]); 77 var r2 = DFS(nums1, nums2, k, start1, pos2 + 1, cur1); 78 79 bool isR1Big = true; 80 for (int i = 0; i < r1.Count; i++) 81 { 82 if (r1[i] < r2[i]) 83 { 84 isR1Big = false; 85 break; 86 } 87 else if (r1[i] > r2[i]) 88 { 89 break; 90 } 91 } 92 93 return isR1Big ? r1 : r2; 94 } 95 } 96 }
以上是关于Leetcode 321: Create Maximum Number的主要内容,如果未能解决你的问题,请参考以下文章