微笔记--为数组重用时,为重新赋值和重新为数组分配空间的差别

以Poj 3356为例子,比较下面两种写法的差别:

import java.util.Scanner;

public class Main {
  //数组初始分配
  static int[][] dp=new int[1001][1001];
	public static int count(String s,int sB,int sE,String t,int tB,int tE){
		if(sB > sE){
			if(tB>tE){
				return 0;
			}else{
				return tE-tB+1;
			}
		}
		if(tB>tE){
			if(sB > sE){
				return 0;
			}else{
				return sE-sB+1;
			}
		}
		if(s.charAt(sB) == t.charAt(tB)){
			if(dp[sB+1][tB+1] == 0){
				dp[sB+1][tB+1]=count(s,sB+1,sE,t,tB+1,tE);
			}
			return dp[sB+1][tB+1];
		}else{
			if(dp[sB][tB+1] == 0){
				dp[sB][tB+1]=count(s,sB,sE,t,tB+1,tE);
			}
			if(dp[sB+1][tB] == 0){
				dp[sB+1][tB]=count(s,sB+1,sE,t,tB,tE);
			}
			if(dp[sB+1][tB+1] == 0){
				dp[sB+1][tB+1]=count(s,sB+1,sE,t,tB+1,tE);
			}
			int min=Math.min(dp[sB][tB+1], dp[sB+1][tB]);
			min=Math.min(min, dp[sB+1][tB+1]);
			return min+1;
		}
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc=new Scanner(System.in);
		//注意这里,赋值重用
		while(sc.hasNext()){
			for(int i=0;i<1001;i++){
				for(int j=0;j<1001;j++){
					dp[i][j]=0;
				}
			}
			int sLen=sc.nextInt();
			String s=sc.next();
			int tLen=sc.nextInt();
			String t=sc.next();
			System.out.println(count(s,0,sLen-1,t,0,tLen-1));
		}
	}
}
import java.util.Scanner;


public class Main {
	static int[][] dp=new int[1001][1001];
	public static int count(String s,int sB,int sE,String t,int tB,int tE){
		if(sB > sE){
			if(tB>tE){
				return 0;
			}else{
				return tE-tB+1;
			}
		}
		if(tB>tE){
			if(sB > sE){
				return 0;
			}else{
				return sE-sB+1;
			}
		}
		if(s.charAt(sB) == t.charAt(tB)){
			if(dp[sB+1][tB+1] == 0){
				dp[sB+1][tB+1]=count(s,sB+1,sE,t,tB+1,tE);
			}
			return dp[sB+1][tB+1];
		}else{
			if(dp[sB][tB+1] == 0){
				dp[sB][tB+1]=count(s,sB,sE,t,tB+1,tE);
			}
			if(dp[sB+1][tB] == 0){
				dp[sB+1][tB]=count(s,sB+1,sE,t,tB,tE);
			}
			if(dp[sB+1][tB+1] == 0){
				dp[sB+1][tB+1]=count(s,sB+1,sE,t,tB+1,tE);
			}
			int min=Math.min(dp[sB][tB+1], dp[sB+1][tB]);
			min=Math.min(min, dp[sB+1][tB+1]);
			return min+1;
		}
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc=new Scanner(System.in);
		//注意这里
		while(sc.hasNext()){
//重新分配内存
                       dp=new int[1001][1001];
                        int sLen=sc.nextInt();
			String s=sc.next();
			int tLen=sc.nextInt();
			String t=sc.next();
			System.out.println(count(s,0,sLen-1,t,0,tLen-1));
		}
	}
}

结果:

第一种:Memory:9136K,Time:219MS

第二种:Memory:32176K,Time:219MS

重新赋值比重新分配的空间用的更多,时间差不多。

你可能感兴趣的:(Java)