查找零和的三元组

时间:2020-06-05 10:48:34

标签: python python-3.x

我正在尝试解决GeeksClasses中的问题,我的提交存在问题。我的代码有效,但是他们说您的程序花了比预期更多的时间。

问题链接: https://practice.geeksforgeeks.org/problems/find-triplets-with-zero-sum/1/?track=SPCF-Sorting&batchId=154

问题陈述:

给出一个整数数组。检查它是否包含一个总计为零的三元组。

输入:

输入的第一行包含一个整数T,表示测试用例的数量。然后是T测试用例。每个测试用例的第一行包含一个整数N,表示数组中元素的数量。每个测试用例的第二行包含N个以空格分隔的数组值。

输出

对于每个测试用例,如果存在三元组,则输出将为1,否则为0

期望的辅助空间:O(1)

预期时间复杂度:O(n2)

示例:

输入:

2

5

0 -1 2 -3 1

3

1 2 3

输出:

1

0

这是我的代码

def isPair(arr,left,right,u):
    while left < right:
        if arr[left] + arr[right] < u:
            left += 1
        elif arr[left] + arr[right] == u:
            return True
        elif arr[left] + arr[right] > u:
            right -= 1
    return False

def findTriplets(a,n):
    #code here
    a = sorted(a)
    for i in range(n):
        if isPair(a,i+1,n-1,0-a[i]):
            return 1
    return 0
#driver code
if __name__=='__main__':
    t=int(input())
    for i in range(t):
        n=int(input())
        a=list(map(int,input().strip().split()))
        print(findTriplets(a,n))



2 个答案:

答案 0 :(得分:1)

这个问题看起来很有趣,这是我们可以使用的两个观察结果。每个有效的三元组都是以下两种形式:

  1. (0,-x,x)
  2. 或(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

答案 1 :(得分: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 );                
    }
}
相关问题