日期:2014-05-20  浏览次数:20683 次

判断一个整数数组,判断其中是否有三个数和为0 求简单的算法或思路
package 数组3个数为0;

public class Test {
public static void main(String[] args) {
int [] a={-5,2,1,14,6,-3};
int x=-1;
for(int i=0;i<a.length;i++){
int q=a[i];
x=i;
x++;
System.out.println("q="+q);
for(int j=x;j<a.length;j++){
System.out.println("第二层"+a[j]);
int w=q+a[j];
System.out.println("w="+w);
x++;
for(int k=x;k<a.length;k++){
System.out.println("第三层"+a[k]);
int e=w+a[k];
System.out.println("e="+e);
if(e==0){
System.out.println("成功"+e);
System.exit(0);
}
}
}
}
}


}


自己写的太复杂了。。 

------解决方案--------------------
随便写了个,看看有哪不对?
public class TestMain {
public static void main(String[] args) {
int[] arr = { -5, 2, 1, 14, 6, -3 };
int sum= 0; //要求的和
calculate(sum,arr);
}

public static void calculate(int sum,int[] arr) {
int count = 0;
for (int i = 0; i <arr.length; i++) {
for (int j = i+1; j <arr.length; j++) {
for (int k = j+1; k <arr.length; k++) {
if (arr[i] + arr[j] + arr[k] == sum) {
count++;
System.out.println("第"+count+"组:"+arr[i]+"+"+arr[j]+"+"+arr[k]+"="+sum);
}
}
}
}
}
}

------解决方案--------------------
/***
 * the times target occur in <code>int[] ints</code>
 * 
 * @param ints
 * @param target
 * @return
 */
public static int count(int[] ints, int target) {
int count = 0;
for (int i = 0; i < ints.length; i++) {