求数组内任意三个数相加和为零的组合

c++实现:

#include 
#include 

using namespace __gnu_cxx;

int main()
{
	int data[100] = {0};
	srand(time(NULL));
	int min = -1000, max = 1000;
	for (int i=0; i<100; i++)
	{
		//随机产生[-1000,1000]的值 
		data[i] = (rand()%(max-min+1))+min;
	}
	//第一步,将数据存入hash_map
	hash_map dataMap;
	for (int i=0; i<100; i++)
	{
		dataMap[data[i]] = i;
	}
	//第二步,遍历数组
	int tmp = 0; 
	for (int i=0; i<100; i++)
	{
		//第三步,二次遍历数组
		for(int j=0; j<100; j++)
		{
			//第四步,从hash_map中匹配值 
			tmp = 0 - data[i] - data[j];
			if (dataMap.find(tmp) != dataMap.end()) {
				printf("(%d)+(%d)+(%d)=0\n", data[i], data[j], tmp);
			}
		} 
	}
	system("pause");
	return 0;
}


java实现:

import java.util.HashMap;
import java.util.Random;

/**
 * Created by Administrator on 2017/1/24.
 */
public class ArraySumZero {
    public static void main(String[] args) {
        int[] data = new int[100];
        int min = -1000, max = 1000;
        Random random = new Random(System.currentTimeMillis());
        for (int i=0; i<100; i++) {
            //随机产生[-1000,1000]的值
            data[i] = random.nextInt(max-min)%(max-min+1) + min;
        }
        //第一步,将数据存入hash_map
        HashMap dataMap = new HashMap();
        for (int i=0; i<100; i++) {
            dataMap.put(data[i], i);
        }
        //第二步,遍历数组
        int tmp = 0;
        for (int i=0; i<100; i++) {
            //第三步,二次遍历数组
            for(int j=0; j<100; j++) {
                //第四步,从hash_map中匹配值
                tmp = 0 - data[i] - data[j];
                if (dataMap.get(tmp) != null) {
                    System.out.printf("(%d)+(%d)+(%d)=0\n", data[i], data[j], tmp);
                }
            }
        }
    }
}


时间复杂度O(n2),空间复杂度O(n)

你可能感兴趣的:(求数组内任意三个数相加和为零的组合)