C# solution based on idea from others


  • 0
    H
    public int[] MaxNumber(int[] nums1, int[] nums2, int k) {
            int m = nums1.Length;
            int n = nums2.Length;
            int[] r = new int[k];
            
            for(int k1 = 0; k1 <= k && k1 <= m; k1++) {
                int k2 = k - k1;
                if (k2 > n) continue;
                int[] d1 = GetMax(nums1, k1);
                int[] d2 = GetMax(nums2, k2);
                int[] d = Merge(d1, d2, k);
                
                // Console.WriteLine("k1={0},d1=[{1}],k2={2},d2=[{3}],d=[{4}]", k1, PrintArray(d1), k2, PrintArray(d2), PrintArray(d));
                if (GreaterThan(d, 0, r, 0)) r = d;
            }
            
            return r;
        }
        
        public string PrintArray(int[] d) {
            StringBuilder sb = new StringBuilder();
            foreach(int dg in d) {
                if (sb.Length > 0) sb.Append(",");
                sb.Append(dg);
            }
            
            return sb.ToString();
        }
        
        public int[] GetMax(int[] nums, int k) {
            int[] d = new int[k];
            int s = 0, n = nums.Length;
            for(int i = 0; i < k; i++) {
                int e = n - k + i;
                if (e < 0 || s >= n) continue;
                int md = s;
                for(int j = md + 1; j <= e; j++) {
                    if (nums[j] > nums[md]) md = j;
                }
                
                // Console.WriteLine("nums.Length={0}, md={1}", nums.Length, md);
                d[i] = nums[md];
                s = md + 1;
            }
            
            return d;
        }
        
        public bool GreaterThan(int[] d1, int i1, int[] d2, int i2) {
            int m = d1.Length;
            int n = d2.Length;
            int i = 0, j = 0;
            
            for(i = i1, j = i2; i < m && j < n && d1[i] == d2[j]; i++, j++) ;
            
            if (j >= n) return true;
            if (i >= m) return false;
            if (d1[i] > d2[j]) return true;
            return false;
        }
        
        public int[] Merge(int[] d1, int[] d2, int k) {
            int m = d1.Length;
            int n = d2.Length;
            int i1 = 0, i2 = 0;
            int[] d = new int[k];
            
            for(int i = 0; i < k; i++) {
                d[i] = GreaterThan(d1, i1, d2, i2) ? d1[i1++] : d2[i2++];
            }
            
            return d;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.