2 回答

TA貢獻(xiàn)2019條經(jīng)驗(yàn) 獲得超9個(gè)贊
這個(gè)問(wèn)題看起來(lái)很有趣,這里有兩個(gè)我們可以使用的觀察結(jié)果。每個(gè)有效的三元組都是以下任一形式:
(0, -x, x)
或 (x, y, z) 使得 x 和 y 與 z 的符號(hào)相反并且 x + y = - z
我會(huì)考慮一種更簡(jiǎn)單的輸入形式,因?yàn)槟拇蟛糠州斎雽?duì)于兩個(gè)整數(shù)列表的內(nèi)容都是多余的,即。example_1 = [[0, -1, 2, -3, 1], [1, 2, 3]]
應(yīng)該導(dǎo)致[1, 0]
.
鑒于我認(rèn)為以下是一個(gè)相當(dāng)快速/可讀的解決方案:
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貢獻(xiàn)1155條經(jīng)驗(yàn) 獲得超0個(gè)贊
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 );
}
}
添加回答
舉報(bào)