[LeetCode] 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 kdigits. 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]

这题挺恶心的,我的做法不太好,勉强通过case(第二遍刷的时候用的Stack容器,而不是数组,变慢了好多)

public class Solution {

    public int[] maxNumber(int[] nums1, int[] nums2, int k) {
    	int[] res=null;
    	for(int i=Math.max(k-nums2.length,0);i<=Math.min(k,nums1.length);i++){
    		int[] a=maxNumber(nums1, i);
    		int[] b=maxNumber(nums2, k-i);
    		int[] re=merge(a,b);
    		if(res==null) res=re;
    		else res=compareTo(res,0,re,0)>0?res:re;
    	}
    	return res;
    }
    public int[] merge(int[] nums1,int[] nums2){
    	int[] re=new int[nums1.length+nums2.length];
    	for(int index=0,i=0,j=0;index<nums1.length+nums2.length;index++){
    		if(i>=nums1.length){
    			re[index]=nums2[j++];
    		}else if(j>=nums2.length){
    			re[index]=nums1[i++];
    		}else{
    			if(compareTo(nums1, i, nums2, j)>0) re[index]=nums1[i++];
    			else re[index]=nums2[j++];
    		}
    	}
    	return re;
    }
    public int[] maxNumber(int[] nums, int k) {
		 if(nums.length<k) return null;
		 int[] stack=new int[1000];
		 int index=0;
		 for(int i=0;i<nums.length;i++){
			 while(index!=0&&nums.length-i+index>k&&stack[index-1]<nums[i]){
				index--;
			 }				 
			 stack[index++]=nums[i];
		 }
		 return Arrays.copyOfRange(stack,0,k);
	 }
    public int compareTo(int[] nums1,int i,int[] nums2,int j){
    	while(i<nums1.length&&j<nums2.length){
    		if(nums1[i]==nums2[j]){
    			i++;j++;
    		}else{
    			return nums1[i]-nums2[j];
    		}
    	}
    	if(nums1.length==i&&nums2.length==j) return 0;
    	else if(i<nums1.length) return 1;
    	else return -1;
    }
    
 
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值