2 回答

TA贡献2019条经验 获得超9个赞
这个问题看起来很有趣,这里有两个我们可以使用的观察结果。每个有效的三元组都是以下任一形式:
(0, -x, x)
或 (x, y, z) 使得 x 和 y 与 z 的符号相反并且 x + y = - z
我会考虑一种更简单的输入形式,因为您的大部分输入对于两个整数列表的内容都是多余的,即。example_1 = [[0, -1, 2, -3, 1], [1, 2, 3]]
应该导致[1, 0]
.
鉴于我认为以下是一个相当快速/可读的解决方案:
from itertools import combinations
def solve_all(inputs):
return [solve(i) for i in inputs]
def solve(single_input):
input_set = set(single_input)
negatives_set = set(-x for x in single_input if x < 0)
positives_set = set(x for x in single_input if x > 0)
if 0 in input_set and len(negatives_set & positives_set) > 0:
return 1
if any(sum(c) in positives_set for c in combinations(negatives_set, 2)):
return 1
if any(sum(c) in negatives_set for c in combinations(positives_set, 2)):
return 1
return 0

TA贡献1155条经验 获得超0个赞
public class FindTriplets{
public static List<List<Integer>> findTriplets(int nums[]) {
boolean found = false;
List<Integer> triples = null;
HashSet<Integer> set = null;
HashSet<List<Integer>> tripleSet = new HashSet<List<Integer>>();
for (int i = 0; i < nums.length - 1; i++) {
set = new HashSet<Integer>();
for (int j = i + 1; j < nums.length; j++) {
found = false;
int x = -(nums[i] + nums[j]);
if (set.contains(x)) {
Integer [] temp = {x,nums[i],nums[j]};
Arrays.sort(temp);
triples = new ArrayList<Integer>();
triples.add(temp[0]);
triples.add(temp[1]);
triples.add(temp[2]);
found = true;
} else {
set.add(nums[j]);
}
if(found==true){
tripleSet.add(triples);
}
}
}
return new ArrayList<List<Integer>>(tripleSet);
}
public static void main(String[] args) {
int arr[] = {0, -1, 2, -3, 1};
//int arr[] = {-1, 0, 1, 2, -1, -4};
List<List<Integer>> triplets = findTriplets(arr);
System.out.println("Triplets : "+triplets );
}
}
添加回答
举报