java中多重循环的简化

要求:4个循环,是否存在和为m的情况。


最暴力的方法,四个for:

public class Forsearch {
	public static void main(String[] args){
		int m = 100;
		int d;
		int[] array = new int[1000];
		//a+b+c+d = m;          d = m -a -b -c;
		double begin = System.currentTimeMillis();
		for(int a=1;a<=1000;a++){
			for(int b=1;b<=1000;b++){
				for(int c=1;c<=1000;c++){
					for(int d=1;d>1000;d++){
                                            if(a+b+c+d==m){
                                                xxxx;
                                            }
                                        }
				}
			}
		}
		double end = System.currentTimeMillis();
		System.out.println(end-begin);
		
	}
}
由于m已给出,可将其中一个未知的d,进行二分查找。

即:d = m-a-b-c;

此时只需要 O(n3) * O(log n)

import java.util.Arrays;


public class Forsearch {
	public static void main(String[] args){
		int m = 4;
		int d;
		int[] array = new int[1000];
		for(int i=0;i<1000;i++){
			array[i]=i+1;
		}
		//a+b+c+d = m;          d = m -a -b -c;
		double begin = System.currentTimeMillis();
		for(int a=1;a<=1000;a++){
			for(int b=1;b<=1000;b++){
				for(int c=1;c<=1000;c++){
					if(Arrays.binarySearch(array, m-a-b-c)!=-1){
						System.out.println(true);
					}
				}
			}
		}
		double end = System.currentTimeMillis();
		System.out.println(end-begin);
		
	}
}
但是这样还是太慢,考虑两个变量都进行二叉查找。但程序中不允许两个求知变量。

所以可以考虑用b,c之和装进一个整个进行查找。

同理,3个4个都可以这样做。

即在4-4000中查找m.

import java.util.Arrays;

public class Forsearch {
	public static void main(String[] args) {
		int m = 4;
		int d;
		int[] array = new int[3996];
		for (int i = 0; i < 3996; i++) {
			array[i] = i + 4;
		}
		if (Arrays.binarySearch(array, m) != -1) {
			System.out.println(true);
		}
		double end = System.currentTimeMillis();

	}
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值