给定一组不同元素。任务是在数组中找到总和等于给定数字的三元组。
例子:
Input: arr[] = {0, -1, 2, -3, 1}
sum = -2
Output: 0 -3 1
-1 2 -3
If we calculate the sum of the output,
0 + (-3) + 1 = -2
(-1) + 2 + (-3) = -2
Input: arr[] = {1, -2, 1, 0, 5}
sum = 0
Output: 1 -2 1
If we calculate the sum of the output,
1 + (-2) + 1 = 0
方法一:蛮力。
方法:此类问题中的蛮力方法旨在检查阵列中存在的所有可能的三元组。 sum=Target sum的三元组就是答案。现在出现的问题是如何检查所有可能的三元组。要检查所有可能的duplets,请在一个元素上固定一个指针,并对每个这样的元素遍历数组并检查总和。这将是所有可能的双胞胎的总和。
同样,为了检查所有可能的三元组,可以固定两个指针并将第三个指针移到数组上,一旦它到达数组末尾,就增加第二个指针并再次重复相同的操作。
算法:
- 取三个指针i , j , k 。
- 用零初始化i并为i启动一个嵌套循环。
- 用(i+1)初始化j并为j启动一个嵌套循环。
- 用(j+1)初始化k并开始循环k 。
- 如果Target == arr[i] + arr[j] + arr[k]中断循环并打印arr[i], arr[j], arr[k] 的值。
- 否则继续增加k直到它等于最后一个 index 。
- 转到步骤2和增量j和对于j的每一个值运行k的内部循环。
- 如果j等于倒数第二个索引转到步骤 1并增加i的值直到倒数第三个索引,然后再次继续整个过程,直到i的值等于最后一个索引。
C++
// A simple C++ program to find three elements
// whose sum is equal to given sum
#include
using namespace std;
// Prints all triplets in arr[] with given sum
void findTriplets(int arr[], int n, int sum)
{
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] == sum) {
cout << arr[i] << " "
<< arr[j] << " "
<< arr[k] << endl;
}
}
}
}
}
// Driver code
int main()
{
int arr[] = { 0, -1, 2, -3, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
findTriplets(arr, n, -2);
return 0;
}
Java
// A simple Java program
// to find three elements
// whose sum is equal to
// given sum
import java.io.*;
class GFG {
// Prints all triplets in
// arr[] with given sum
static void findTriplets(int arr[],
int n, int sum)
{
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] == sum) {
System.out.println(
arr[i] + " " + arr[j]
+ " " + arr[k]);
}
}
}
}
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 0, -1, 2, -3, 1 };
int n = arr.length;
findTriplets(arr, n, -2);
}
}
// This code is contributed by m_kit
Python3
# A simple Python 3 program
# to find three elements
# whose sum is equal to
# given sum
# Prints all triplets in
# arr[] with given sum
def findTriplets(arr, n, sum):
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] == sum):
print(arr[i], " ",
arr[j], " ",
arr[k], sep = "")
# Driver code
arr = [ 0, -1, 2, -3, 1 ]
n = len(arr)
findTriplets(arr, n, -2)
# This code is contributed
# by Smitha
C#
// A simple C# program
// to find three elements
// whose sum is equal to
// given sum
using System;
class GFG {
// Prints all triplets in
// arr[] with given sum
static void findTriplets(int[] arr,
int n, int sum)
{
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] == sum) {
Console.WriteLine(
arr[i] + " " + arr[j]
+ " " + arr[k]);
}
}
}
}
}
// Driver code
static public void Main()
{
int[] arr = { 0, -1, 2, -3, 1 };
int n = arr.Length;
findTriplets(arr, n, -2);
}
}
// This code is contributed by akt_mit
PHP
Javascript
C++
// C++ program to find triplets in a given
// array whose sum is equal to given sum.
#include
using namespace std;
// function to print triplets with given sum
void findTriplets(int arr[], int n, int sum)
{
for (int i = 0; i < n - 1; i++) {
// Find all pairs with sum equals to
// "sum-arr[i]"
unordered_set s;
for (int j = i + 1; j < n; j++) {
int x = sum - (arr[i] + arr[j]);
if (s.find(x) != s.end())
printf("%d %d %d\n", x, arr[i], arr[j]);
else
s.insert(arr[j]);
}
}
}
// Driver code
int main()
{
int arr[] = { 0, -1, 2, -3, 1 };
int sum = -2;
int n = sizeof(arr) / sizeof(arr[0]);
findTriplets(arr, n, sum);
return 0;
}
Java
// Java program to find triplets in a given
// array whose sum is equal to given sum.
import java.util.*;
class GFG {
// function to print triplets with given sum
static void findTriplets(int arr[], int n, int sum)
{
for (int i = 0; i < n - 1; i++) {
// Find all pairs with sum equals to
// "sum-arr[i]"
HashSet s = new HashSet<>();
for (int j = i + 1; j < n; j++) {
int x = sum - (arr[i] + arr[j]);
if (s.contains(x))
System.out.printf(
"%d %d %d\n", x, arr[i], arr[j]);
else
s.add(arr[j]);
}
}
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 0, -1, 2, -3, 1 };
int sum = -2;
int n = arr.length;
findTriplets(arr, n, sum);
}
}
// This code is contributed by Rajput-Ji
Python3
# Python3 program to find triplets in a given
# array whose Sum is equal to given sum.
import math as mt
# function to print triplets with given sum
def findTriplets(arr, n, Sum):
for i in range(n - 1):
# Find all pairs with Sum equals
# to "Sum-arr[i]"
s = dict()
for j in range(i + 1, n):
x = Sum - (arr[i] + arr[j])
if x in s.keys():
print(x, arr[i], arr[j])
else:
s[arr[j]] = 1
# Driver code
arr = [ 0, -1, 2, -3, 1 ]
Sum = -2
n = len(arr)
findTriplets(arr, n, Sum)
# This code is contributed
# by mohit kumar 29
C#
// C# program to find triplets in a given
// array whose sum is equal to given sum.
using System;
using System.Collections.Generic;
public class GFG {
// function to print triplets with given sum
static void findTriplets(int[] arr, int n, int sum)
{
for (int i = 0; i < n - 1; i++) {
// Find all pairs with sum equals to
// "sum-arr[i]"
HashSet s = new HashSet();
for (int j = i + 1; j < n; j++) {
int x = sum - (arr[i] + arr[j]);
if (s.Contains(x))
Console.Write("{0} {1} {2}\n", x, arr[i], arr[j]);
else
s.Add(arr[j]);
}
}
}
// Driver code
public static void Main(String[] args)
{
int[] arr = { 0, -1, 2, -3, 1 };
int sum = -2;
int n = arr.Length;
findTriplets(arr, n, sum);
}
}
// This code is contributed by Princi Singh
Javascript
C++
// C++ program to find triplets in a given
// array whose sum is given sum.
#include
using namespace std;
// Function to print triplets with given sum
vector> findTriplets(int nums[],int n,int sumTarget) {
vector> res;
if(n <=2) return res;
sort(nums,nums + n);
for(int i=0;i0 && nums[i] == nums[i-1]) // avoid duplicate triplets count
continue;
int num = nums[i];
int target = sumTarget - num;
for(int l=i+1, r=n-1; l target)
r--;
else if (nums[l]+nums[r] < target)
l++;
else {
// nums[l] + nums[r] == target
res.push_back({nums[i], nums[l], nums[r]});
// skip duplicates
while( l0 && nums[r]==nums[r-1]) r--;
l++;
r--;
}
}
}
return res;
}
// Driver code
int main()
{
int arr[] = { 0, -1, 2, -3, 1, -1, 3, 0};
int sum = -2;
int n = sizeof(arr) / sizeof(arr[0]);
vector> res = findTriplets(arr, n, sum);
cout<<"Unique triplets found are : \n";
for(int i = 0;i
Java
// Java program to find triplets
// in a given array whose sum
// is given sum.
import java.io.*;
import java.util.*;
class GFG {
// function to print
// triplets with given sum
static void findTriplets(int[] arr,
int n, int sum)
{
// sort array elements
Arrays.sort(arr);
for (int i = 0;
i < n - 1; i++) {
// initialize left and right
int l = i + 1;
int r = n - 1;
int x = arr[i];
while (l < r) {
if (x + arr[l] + arr[r] == sum) {
// print elements if it's
// sum is given sum.
System.out.println(
x + " " + arr[l] + " "
+ arr[r]);
l++;
r--;
}
// If sum of three elements
// is less than 'sum' then
// increment in left
else if (x + arr[l] + arr[r] < sum)
l++;
// if sum is greater than
// given sum, then decrement
// in right side
else
r--;
}
}
}
// Driver code
public static void main(String args[])
{
int[] arr = new int[] { 0, -1, 2, -3, 1 };
int sum = -2;
int n = arr.length;
findTriplets(arr, n, sum);
}
}
// This code is contributed
// by Akanksha Rai(Abby_akku)
Python3
# Python3 program to find triplets in a
# given array whose sum is given sum.
# function to print triplets with
# given sum
def findTriplets(arr, n, sum):
# 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] == sum) :
# print elements if it's sum
# is given sum.
print(x, arr[l], arr[r]);
l = l + 1;
r = r - 1;
# If sum of three elements is less
# than 'sum' then increment in left
elif (x + arr[l] + arr[r] < sum):
l = l + 1;
# if sum is greater than given sum,
# then decrement in right side
else:
r = r - 1;
# Driver code
arr = [ 0, -1, 2, -3, 1 ];
sum = -2;
n = len(arr);
findTriplets(arr, n, sum);
# This code is contributed by
# Shivi_Aggarwal
C#
// C# program to find triplets
// in a given array whose sum
// is given sum.
using System;
class GFG {
// function to print
// triplets with given sum
static void findTriplets(int[] arr,
int n, int sum)
{
// sort array elements
Array.Sort(arr);
for (int i = 0; i < n - 1; i++) {
// initialize left and right
int l = i + 1;
int r = n - 1;
int x = arr[i];
while (l < r) {
if (x + arr[l] + arr[r] == sum) {
// print elements if it's
// sum is given sum.
Console.WriteLine(x + " " + arr[l] + " " + arr[r]);
l++;
r--;
}
// If sum of three elements
// is less than 'sum' then
// increment in left
else if (x + arr[l] + arr[r] < sum)
l++;
// if sum is greater than
// given sum, then decrement
// in right side
else
r--;
}
}
}
// Driver code
static int Main()
{
int[] arr = new int[] { 0, -1, 2, -3, 1 };
int sum = -2;
int n = arr.Length;
findTriplets(arr, n, sum);
return 0;
}
}
// This code is contributed by rahul
PHP
Javascript
0 -3 1
-1 2 -3
复杂度分析:
- 时间复杂度: O(n 3 )。
因为已经使用了三个嵌套的 for 循环。 - 辅助空间: O(1)。
因为没有数据结构用于存储值。
方法2 :散列。
方法:
散列可以用来解决这个问题。 HashTable 或 HashMaps 允许我们以恒定的时间复杂度执行查找或搜索操作。如果可以发现对于每个可能的二元组,数组中已经存在一个可以使sum=target sum的元素,那么问题将以有效的方式解决。
为了实现哈希,我们可以使用 C++ 中的 unordered_set 或Java的HashSet。
- 当我们修复第一个指针(比如 a)时,使用第二个指针(比如 b)遍历数组并继续存储在HashTable 中遇到的元素。
- 一旦我们发现HashTable 中已经存在的元素等于剩余总和(Target sum -(a+b)) ,我们就打印我们的三元组。
算法:
- 从i=0开始外循环,直到第(n-2) 个索引。
- 对于每次迭代,创建一个无序集合并进入内部循环。
- 开始内部循环[ from j = (i+1) (因为我们已经检查过的值不会出现在有效的三元组中)直到最后一个索引。
- 检查元素x = Target -(arr[i] + arr[j])是否存在,然后找到并打印三元组。
- 否则推送集合中的值以供以后参考。
- 递增i并转到第 2 步。
伪代码:
Run a loop from i=0 to n-2
Create an empty hash table
Run inner loop from j=i+1 to n-1
If -(arr[i] + arr[j]) is present in hash table
print arr[i], arr[j] and -(arr[i] + arr[j])
Else
Insert arr[j] in hash table.
C++
// C++ program to find triplets in a given
// array whose sum is equal to given sum.
#include
using namespace std;
// function to print triplets with given sum
void findTriplets(int arr[], int n, int sum)
{
for (int i = 0; i < n - 1; i++) {
// Find all pairs with sum equals to
// "sum-arr[i]"
unordered_set s;
for (int j = i + 1; j < n; j++) {
int x = sum - (arr[i] + arr[j]);
if (s.find(x) != s.end())
printf("%d %d %d\n", x, arr[i], arr[j]);
else
s.insert(arr[j]);
}
}
}
// Driver code
int main()
{
int arr[] = { 0, -1, 2, -3, 1 };
int sum = -2;
int n = sizeof(arr) / sizeof(arr[0]);
findTriplets(arr, n, sum);
return 0;
}
Java
// Java program to find triplets in a given
// array whose sum is equal to given sum.
import java.util.*;
class GFG {
// function to print triplets with given sum
static void findTriplets(int arr[], int n, int sum)
{
for (int i = 0; i < n - 1; i++) {
// Find all pairs with sum equals to
// "sum-arr[i]"
HashSet s = new HashSet<>();
for (int j = i + 1; j < n; j++) {
int x = sum - (arr[i] + arr[j]);
if (s.contains(x))
System.out.printf(
"%d %d %d\n", x, arr[i], arr[j]);
else
s.add(arr[j]);
}
}
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 0, -1, 2, -3, 1 };
int sum = -2;
int n = arr.length;
findTriplets(arr, n, sum);
}
}
// This code is contributed by Rajput-Ji
蟒蛇3
# Python3 program to find triplets in a given
# array whose Sum is equal to given sum.
import math as mt
# function to print triplets with given sum
def findTriplets(arr, n, Sum):
for i in range(n - 1):
# Find all pairs with Sum equals
# to "Sum-arr[i]"
s = dict()
for j in range(i + 1, n):
x = Sum - (arr[i] + arr[j])
if x in s.keys():
print(x, arr[i], arr[j])
else:
s[arr[j]] = 1
# Driver code
arr = [ 0, -1, 2, -3, 1 ]
Sum = -2
n = len(arr)
findTriplets(arr, n, Sum)
# This code is contributed
# by mohit kumar 29
C#
// C# program to find triplets in a given
// array whose sum is equal to given sum.
using System;
using System.Collections.Generic;
public class GFG {
// function to print triplets with given sum
static void findTriplets(int[] arr, int n, int sum)
{
for (int i = 0; i < n - 1; i++) {
// Find all pairs with sum equals to
// "sum-arr[i]"
HashSet s = new HashSet();
for (int j = i + 1; j < n; j++) {
int x = sum - (arr[i] + arr[j]);
if (s.Contains(x))
Console.Write("{0} {1} {2}\n", x, arr[i], arr[j]);
else
s.Add(arr[j]);
}
}
}
// Driver code
public static void Main(String[] args)
{
int[] arr = { 0, -1, 2, -3, 1 };
int sum = -2;
int n = arr.Length;
findTriplets(arr, n, sum);
}
}
// This code is contributed by Princi Singh
Javascript
-3 0 1
2 -1 -3
复杂度分析:
- 时间复杂度: O(n 2 )。
使用嵌套的 for 循环会使时间复杂度达到 n 2 。 - 辅助空间: O(n)。
由于 unordered_set 数据结构已用于存储值。
方法三:该方法采用排序和两点法来解决上述问题。此执行将涉及 O(n 2 )) 时间复杂度和 O(1) 空间复杂度。这个想法是基于这篇文章的方法 2。
方法:可以使用排序技术将两个指针技术付诸实践。在双指针技术中,可以在线性时间内搜索具有目标和的对。这里的想法是修复一个指针(比如 a) ,并使用剩余的指针高效地找到具有所需总和Target-value at(a) 的对。
现在让我们讨论如何使用两个指针技术有效地找到所需的对。用于两个指针技术的指针是 say (l 和 r) 。
- 因此,如果sum = value(a) + value(l) + value(r)超过了所需的总和,对于相同的(a, l) ,所需的value(r)应该小于之前的值。因此,递减r指针。
- 如果sum = value(a) + value(l) + value(r)小于所需的总和,对于相同的(a, r) ,所需的value(l)应该大于之前的值。因此,增加l指针。
算法:
- 对数组进行排序,并为每个元素arr[i]搜索其他两个元素arr[l], arr[r]使得arr[i]+arr[l]+arr[r]=Target sum 。
- 在对数组进行排序时,可以使用双指针技术有效地搜索其他两个元素。
- 运行一个外部循环,将控制变量作为i,并为每次迭代初始化一个值l ,它是第一个带有i+1 的指针和带有最后一个索引的r 。
- 现在进入一个 while 循环,它将运行到l
的值。 - 如果arr[i]+arr[l]+arr[r]>Target sum然后将r减1,因为所需的总和小于当前总和,并且减小 的值将是必要的。
- 如果ARR [I] + ARR [1] + ARR [R] <目标总和然后增量升由1作为所需总和小于当前总和和增加将做要紧的值。
- 如果arr[i]+arr[l]+arr[r]==Target sum打印值。
- 递增i转到步骤 3。
伪代码:
1. Sort all element of array
2. Run loop from i=0 to n-2.
Initialize two index variables l=i+1 and r=n-1
4. while (l < r)
Check sum of arr[i], arr[l], arr[r] is
given sum or not if sum is 'sum', then print
the triplet and do l++ and r--.
5. If sum is less than given sum then l++
6. If sum is greater than given sum then r--
7. If not exist in array then print not found.
C++
// C++ program to find triplets in a given
// array whose sum is given sum.
#include
using namespace std;
// Function to print triplets with given sum
vector> findTriplets(int nums[],int n,int sumTarget) {
vector> res;
if(n <=2) return res;
sort(nums,nums + n);
for(int i=0;i0 && nums[i] == nums[i-1]) // avoid duplicate triplets count
continue;
int num = nums[i];
int target = sumTarget - num;
for(int l=i+1, r=n-1; l target)
r--;
else if (nums[l]+nums[r] < target)
l++;
else {
// nums[l] + nums[r] == target
res.push_back({nums[i], nums[l], nums[r]});
// skip duplicates
while( l0 && nums[r]==nums[r-1]) r--;
l++;
r--;
}
}
}
return res;
}
// Driver code
int main()
{
int arr[] = { 0, -1, 2, -3, 1, -1, 3, 0};
int sum = -2;
int n = sizeof(arr) / sizeof(arr[0]);
vector> res = findTriplets(arr, n, sum);
cout<<"Unique triplets found are : \n";
for(int i = 0;i
Java
// Java program to find triplets
// in a given array whose sum
// is given sum.
import java.io.*;
import java.util.*;
class GFG {
// function to print
// triplets with given sum
static void findTriplets(int[] arr,
int n, int sum)
{
// sort array elements
Arrays.sort(arr);
for (int i = 0;
i < n - 1; i++) {
// initialize left and right
int l = i + 1;
int r = n - 1;
int x = arr[i];
while (l < r) {
if (x + arr[l] + arr[r] == sum) {
// print elements if it's
// sum is given sum.
System.out.println(
x + " " + arr[l] + " "
+ arr[r]);
l++;
r--;
}
// If sum of three elements
// is less than 'sum' then
// increment in left
else if (x + arr[l] + arr[r] < sum)
l++;
// if sum is greater than
// given sum, then decrement
// in right side
else
r--;
}
}
}
// Driver code
public static void main(String args[])
{
int[] arr = new int[] { 0, -1, 2, -3, 1 };
int sum = -2;
int n = arr.length;
findTriplets(arr, n, sum);
}
}
// This code is contributed
// by Akanksha Rai(Abby_akku)
蟒蛇3
# Python3 program to find triplets in a
# given array whose sum is given sum.
# function to print triplets with
# given sum
def findTriplets(arr, n, sum):
# 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] == sum) :
# print elements if it's sum
# is given sum.
print(x, arr[l], arr[r]);
l = l + 1;
r = r - 1;
# If sum of three elements is less
# than 'sum' then increment in left
elif (x + arr[l] + arr[r] < sum):
l = l + 1;
# if sum is greater than given sum,
# then decrement in right side
else:
r = r - 1;
# Driver code
arr = [ 0, -1, 2, -3, 1 ];
sum = -2;
n = len(arr);
findTriplets(arr, n, sum);
# This code is contributed by
# Shivi_Aggarwal
C#
// C# program to find triplets
// in a given array whose sum
// is given sum.
using System;
class GFG {
// function to print
// triplets with given sum
static void findTriplets(int[] arr,
int n, int sum)
{
// sort array elements
Array.Sort(arr);
for (int i = 0; i < n - 1; i++) {
// initialize left and right
int l = i + 1;
int r = n - 1;
int x = arr[i];
while (l < r) {
if (x + arr[l] + arr[r] == sum) {
// print elements if it's
// sum is given sum.
Console.WriteLine(x + " " + arr[l] + " " + arr[r]);
l++;
r--;
}
// If sum of three elements
// is less than 'sum' then
// increment in left
else if (x + arr[l] + arr[r] < sum)
l++;
// if sum is greater than
// given sum, then decrement
// in right side
else
r--;
}
}
}
// Driver code
static int Main()
{
int[] arr = new int[] { 0, -1, 2, -3, 1 };
int sum = -2;
int n = arr.Length;
findTriplets(arr, n, sum);
return 0;
}
}
// This code is contributed by rahul
PHP
Javascript
-3 -1 2
-3 0 1
复杂度分析:
- 时间复杂度: O(n 2 )。
使用嵌套循环(一个用于迭代,另一个用于双指针技术)使时间复杂度变为 O(n 2 )。 - 辅助空间: O(1)。
因为没有使用额外的数据结构。
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。