LeetCode算法题——给定数组求可满足的三元组

题目

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
  [-1, 0, 1],
  [-1, -1, 2]
]
 

代码实现

public class demo {
	
	public static HashMap findTriple(HashMap map1,HashMap map2) {
		
		int result_index = 0;
		HashMap last_over = new HashMap<>();
		String[] result = new String[100];
		
		//第一个for循环表示map1的元素从左到右移动长度
		for(int i=0;i=0) {
			System.out.println("该数组中不存在三元组");
		}else if(first[first.length-1]<=0){
			System.out.println("该数组中不存在三元组");
		}else {
			
			HashMap map1 = new HashMap<>();
			HashMap map2 = new HashMap<>();
			
			int map1_index = 0;
			int map2_index = 0;
			
			for(int i=0;i end1 = findTriple(map1, map2);
			HashMap end2 = findTriple(map2, map1);
			
			ArrayList over = new ArrayList<>();
			for(String key:end1.keySet()) {
				over.add(key);
			}
			for(String key:end2.keySet()) {
				over.add(key);
			}
			
			if(map2_0==3) {
				over.add("["+0+","+0+","+0+"]");
			}
			
			if(over.size()==0) {
				System.out.println("该数组中不存在三元组");
			}else {
				System.out.println(over);
			}			
		}
	}
}

 

你可能感兴趣的:(算法)