📜  找出所有零和的三元组

📅  最后修改于: 2021-10-27 08:15:51             🧑  作者: Mango

给定一组不同元素。任务是在数组中找到总和为零的三元组。

例子 :

Input : arr[] = {0, -1, 2, -3, 1}
Output : (0 -1 1), (2 -3 1)

Explanation : The triplets with zero sum are
0 + -1 + 1 = 0 and 2 + -3 + 1 = 0  

Input : arr[] = {1, -2, 1, 0, 5}
Output : 1 -2  1
Explanation : The triplets with zero sum is
1 + -2 + 1 = 0   

方法 1:这是一个简单的方法,需要 O(n 3 ) 时间才能得出结果。

  • 方法:天真的方法运行三个循环并一一检查三个元素的总和是否为零。如果三个元素的总和为零,则打印元素,否则打印未找到。
  • 算法:
    1. 使用循环计数器ijk运行三个嵌套循环
    2. 第一个循环从 0 到 n-3,第二个循环从 i+1 到 n-2,第三个循环从 j+1 到 n-1。循环计数器代表三元组的三个元素。
    3. 检查第 i’th、j’th、k’th 处元素的总和是否等于 0。如果是,则打印总和,否则继续。

下面是上述方法的实现:

C++
// A simple C++ program to find three elements
// whose sum is equal to zero
#include
using namespace std;
 
// Prints all triplets in arr[] with 0 sum
void findTriplets(int arr[], int n)
{
    bool found = false;
    for (int i=0; i


Java
// A simple Java program to find three elements
// whose sum is equal to zero
class num{
// Prints all triplets in arr[] with 0 sum
static void findTriplets(int[] arr, int n)
{
    boolean found = false;
    for (int i=0; i


Python3
# A simple Python 3 program
# to find three elements whose
# sum is equal to zero
 
# Prints all triplets in
# arr[] with 0 sum
def findTriplets(arr, n):
 
    found = False
    for i in range(0, n-2):
     
        for j in range(i+1, n-1):
         
            for k in range(j+1, n):
             
                if (arr[i] + arr[j] + arr[k] == 0):
                    print(arr[i], arr[j], arr[k])
                    found = True
     
             
    # If no triplet with 0 sum
    # found in array
    if (found == False):
        print(" not exist ")
 
# Driver code
arr = [0, -1, 2, -3, 1]
n = len(arr)
findTriplets(arr, n)
 
# This code is contributed by Smitha Dinesh Semwal


C#
// A simple C# program to find three elements
// whose sum is equal to zero
using System;
 
class GFG {
     
    // Prints all triplets in arr[] with 0 sum
    static void findTriplets(int []arr, int n)
    {
        bool found = false;
        for (int i = 0; i < n-2; i++)
        {
            for (int j = i+1; j < n-1; j++)
            {
                for (int k = j+1; k < n; k++)
                {
                    if (arr[i] + arr[j] + arr[k]
                                           == 0)
                    {
                        Console.Write(arr[i]);
                        Console.Write(" ");
                        Console.Write(arr[j]);
                        Console.Write(" ");
                        Console.Write(arr[k]);
                        Console.Write("\n");
                        found = true;
                    }
                }
            }
        }
     
        // If no triplet with 0 sum found in
        // array
        if (found == false)
            Console.Write(" not exist ");
    }
     
    // Driver code
    public static void Main()
    {
        int []arr = {0, -1, 2, -3, 1};
        int n = arr.Length;
        findTriplets(arr, n);
    }
}
 
// This code is contributed by nitin mittal.


PHP


Javascript


C++
// C++ program to find triplets in a given
// array whose sum is zero
#include
using namespace std;
 
// function to print triplets with 0 sum
void findTriplets(int arr[], int n)
{
    bool found = false;
 
    for (int i=0; i s;
        for (int j=i+1; j


Java
// Java program to find triplets in a given
// array whose sum is zero
import java.util.*;
 
class GFG
{
 
    // function to print triplets with 0 sum
    static void findTriplets(int arr[], int n)
    {
        boolean found = false;
 
        for (int i = 0; i < n - 1; i++)
        {
            // Find all pairs with sum equals to
            // "-arr[i]"
            HashSet s = new HashSet();
            for (int j = i + 1; j < n; j++)
            {
                int x = -(arr[i] + arr[j]);
                if (s.contains(x))
                {
                    System.out.printf("%d %d %d\n", x, arr[i], arr[j]);
                    found = true;
                }
                else
                {
                    s.add(arr[j]);
                }
            }
        }
 
        if (found == false)
        {
            System.out.printf(" No Triplet Found\n");
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = {0, -1, 2, -3, 1};
        int n = arr.length;
        findTriplets(arr, n);
    }
}
 
// This code contributed by Rajput-Ji


Python3
# Python3 program to find triplets
# in a given array whose sum is zero
 
# function to print triplets with 0 sum
def findTriplets(arr, n):
    found = False
    for i in range(n - 1):
 
        # Find all pairs with sum
        # equals to "-arr[i]"
        s = set()
        for j in range(i + 1, n):
            x = -(arr[i] + arr[j])
            if x in s:
                print(x, arr[i], arr[j])
                found = True
            else:
                s.add(arr[j])
    if found == False:
        print("No Triplet Found")
 
# Driver Code
arr = [0, -1, 2, -3, 1]
n = len(arr)
findTriplets(arr, n)
 
# This code is contributed by Shrikant13


C#
// C# program to find triplets in a given
// array whose sum is zero
using System;
using System.Collections.Generic;
 
class GFG
{
 
    // function to print triplets with 0 sum
    static void findTriplets(int []arr, int n)
    {
        bool found = false;
 
        for (int i = 0; i < n - 1; i++)
        {
            // Find all pairs with sum equals to
            // "-arr[i]"
            HashSet s = new HashSet();
            for (int j = i + 1; j < n; j++)
            {
                int x = -(arr[i] + arr[j]);
                if (s.Contains(x))
                {
                    Console.Write("{0} {1} {2}\n", x, arr[i], arr[j]);
                    found = true;
                }
                else
                {
                    s.Add(arr[j]);
                }
            }
        }
 
        if (found == false)
        {
            Console.Write(" No Triplet Found\n");
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int []arr = {0, -1, 2, -3, 1};
        int n = arr.Length;
        findTriplets(arr, n);
    }
}
 
// This code has been contributed by 29AjayKumar


Javascript


C++
// C++ program to find triplets in a given
// array whose sum is zero
#include
using namespace std;
 
// function to print triplets with 0 sum
void findTriplets(int arr[], int n)
{
    bool found = false;
 
    // sort array elements
    sort(arr, arr+n);
 
    for (int i=0; i


Java
// Java  program to find triplets in a given
// array whose sum is zero
import java.util.Arrays;
import java.io.*;
 
class GFG {
    // function to print triplets with 0 sum
static void findTriplets(int arr[], int n)
{
    boolean found = false;
 
    // sort array elements
    Arrays.sort(arr);
 
    for (int i=0; i


Python3
# python program to find triplets in a given
# array whose sum is zero
 
# function to print triplets with 0 sum
def findTriplets(arr, n):
 
    found = False
 
    # sort array elements
    arr.sort()
 
    for i in range(0, n-1):
     
        # initialize left and right
        l = i + 1
        r = n - 1
        x = arr[i]
        while (l < r):
         
            if (x + arr[l] + arr[r] == 0):
                # print elements if it's sum is zero
                print(x, arr[l], arr[r])
                l+=1
                r-=1
                found = True
             
 
            # If sum of three elements is less
            # than zero then increment in left
            elif (x + arr[l] + arr[r] < 0):
                l+=1
 
            # if sum is greater than zero than
            # decrement in right side
            else:
                r-=1
         
    if (found == False):
        print(" No Triplet Found")
 
 
# Driven source
arr = [0, -1, 2, -3, 1]
n = len(arr)
findTriplets(arr, n)
 
# This code is contributed by Smitha Dinesh Semwal


C#
// C#  program to find triplets in a given
// array whose sum is zero
using System;
 
public class GFG{
        // function to print triplets with 0 sum
static void findTriplets(int []arr, int n)
{
    bool found = false;
 
    // sort array elements
    Array.Sort(arr);
 
    for (int i=0; i


PHP


Javascript


输出

0 -1 1
2 -3 1

复杂度分析:

  • 时间复杂度: O(n 3 )。
    由于需要三个嵌套循环,所以时间复杂度为 O(n 3 )。
  • 辅助空间: O(1)。
    由于不需要额外的空间,所以空间复杂度是恒定的。

方法2:第二种方法使用Hashing的过程得出结果,并在O(n 2 )更短的时间内求解。

方法:这涉及遍历数组。对于每个元素 arr[i],找到一个总和为“-arr[i]”的对。这个问题简化为对和,可以使用散列在 O(n) 时间内解决。

算法:

  1. 创建一个 hashmap 来存储一个键值对。
  2. 运行包含两个循环的嵌套循环,外循环从 0 到 n-2,内循环从 i+1 到 n-1
  3. 检查哈希图中是否存在第 i 个和第 j 个元素乘以 -1 的总和
  4. 如果该元素存在于哈希图中,则打印三元组,否则在哈希图中插入第 j 个元素。

下面是上述方法的实现:

C++

// C++ program to find triplets in a given
// array whose sum is zero
#include
using namespace std;
 
// function to print triplets with 0 sum
void findTriplets(int arr[], int n)
{
    bool found = false;
 
    for (int i=0; i s;
        for (int j=i+1; j

Java

// Java program to find triplets in a given
// array whose sum is zero
import java.util.*;
 
class GFG
{
 
    // function to print triplets with 0 sum
    static void findTriplets(int arr[], int n)
    {
        boolean found = false;
 
        for (int i = 0; i < n - 1; i++)
        {
            // Find all pairs with sum equals to
            // "-arr[i]"
            HashSet s = new HashSet();
            for (int j = i + 1; j < n; j++)
            {
                int x = -(arr[i] + arr[j]);
                if (s.contains(x))
                {
                    System.out.printf("%d %d %d\n", x, arr[i], arr[j]);
                    found = true;
                }
                else
                {
                    s.add(arr[j]);
                }
            }
        }
 
        if (found == false)
        {
            System.out.printf(" No Triplet Found\n");
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = {0, -1, 2, -3, 1};
        int n = arr.length;
        findTriplets(arr, n);
    }
}
 
// This code contributed by Rajput-Ji

蟒蛇3

# Python3 program to find triplets
# in a given array whose sum is zero
 
# function to print triplets with 0 sum
def findTriplets(arr, n):
    found = False
    for i in range(n - 1):
 
        # Find all pairs with sum
        # equals to "-arr[i]"
        s = set()
        for j in range(i + 1, n):
            x = -(arr[i] + arr[j])
            if x in s:
                print(x, arr[i], arr[j])
                found = True
            else:
                s.add(arr[j])
    if found == False:
        print("No Triplet Found")
 
# Driver Code
arr = [0, -1, 2, -3, 1]
n = len(arr)
findTriplets(arr, n)
 
# This code is contributed by Shrikant13

C#

// C# program to find triplets in a given
// array whose sum is zero
using System;
using System.Collections.Generic;
 
class GFG
{
 
    // function to print triplets with 0 sum
    static void findTriplets(int []arr, int n)
    {
        bool found = false;
 
        for (int i = 0; i < n - 1; i++)
        {
            // Find all pairs with sum equals to
            // "-arr[i]"
            HashSet s = new HashSet();
            for (int j = i + 1; j < n; j++)
            {
                int x = -(arr[i] + arr[j]);
                if (s.Contains(x))
                {
                    Console.Write("{0} {1} {2}\n", x, arr[i], arr[j]);
                    found = true;
                }
                else
                {
                    s.Add(arr[j]);
                }
            }
        }
 
        if (found == false)
        {
            Console.Write(" No Triplet Found\n");
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int []arr = {0, -1, 2, -3, 1};
        int n = arr.Length;
        findTriplets(arr, n);
    }
}
 
// This code has been contributed by 29AjayKumar

Javascript


输出
-1 0 1
-3 2 1

复杂度分析:

  • 时间复杂度: O(n 2 )。
    由于需要两个嵌套循环,所以时间复杂度为 O(n 2 )。
  • 辅助空间: O(n)。
    由于需要hashmap,所以空间复杂度是线性的。

方法 3:该方法使用 Sorting 得出正确结果,并在 O(n 2 ) 时间内求解。

方法:上述方法需要额外的空间。这个想法是基于这篇文章的方法 2。对于每个元素,检查是否有一对总和等于该元素的负值。

算法:

  1. 按升序对数组进行排序。
  2. 从头到尾遍历数组。
  3. 对于每个索引i ,创建两个变量l = i + 1r = n – 1
  4. 如果 array[i]、array[l] 和 array[r] 的和等于 0,则运行循环直到 l 小于 r,然后打印三元组并中断循环
  5. 如果总和小于零,则增加 l 的值,通过增加 l 的值,总和将随着数组排序而增加,因此array[l+1] > array [l]
  6. 如果总和大于零,则减少 r 的值,通过增加 l 的值,总和将随着数组的排序而减少,因此array[r-1] < array [r]

下面是上述方法的实现:

C++

// C++ program to find triplets in a given
// array whose sum is zero
#include
using namespace std;
 
// function to print triplets with 0 sum
void findTriplets(int arr[], int n)
{
    bool found = false;
 
    // sort array elements
    sort(arr, arr+n);
 
    for (int i=0; i

Java

// Java  program to find triplets in a given
// array whose sum is zero
import java.util.Arrays;
import java.io.*;
 
class GFG {
    // function to print triplets with 0 sum
static void findTriplets(int arr[], int n)
{
    boolean found = false;
 
    // sort array elements
    Arrays.sort(arr);
 
    for (int i=0; i

蟒蛇3

# python program to find triplets in a given
# array whose sum is zero
 
# function to print triplets with 0 sum
def findTriplets(arr, n):
 
    found = False
 
    # sort array elements
    arr.sort()
 
    for i in range(0, n-1):
     
        # initialize left and right
        l = i + 1
        r = n - 1
        x = arr[i]
        while (l < r):
         
            if (x + arr[l] + arr[r] == 0):
                # print elements if it's sum is zero
                print(x, arr[l], arr[r])
                l+=1
                r-=1
                found = True
             
 
            # If sum of three elements is less
            # than zero then increment in left
            elif (x + arr[l] + arr[r] < 0):
                l+=1
 
            # if sum is greater than zero than
            # decrement in right side
            else:
                r-=1
         
    if (found == False):
        print(" No Triplet Found")
 
 
# Driven source
arr = [0, -1, 2, -3, 1]
n = len(arr)
findTriplets(arr, n)
 
# This code is contributed by Smitha Dinesh Semwal

C#

// C#  program to find triplets in a given
// array whose sum is zero
using System;
 
public class GFG{
        // function to print triplets with 0 sum
static void findTriplets(int []arr, int n)
{
    bool found = false;
 
    // sort array elements
    Array.Sort(arr);
 
    for (int i=0; i

PHP


Javascript


输出
-3 1 2
-1 0 1

复杂度分析:

  • 时间复杂度: O(n 2 )。
    只需要两个嵌套循环,因此时间复杂度为 O(n 2 )。
  • 辅助空间: O(1),不需要额外的空间,所以时间复杂度是常数。

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程