数组中的三元组和 (3sum)
给定一个大小为 n 的数组 arr[] 和一个整数 X。查找数组中是否存在一个三元组,其总和等于给定的整数 X。
例子:
输入:数组 = {12, 3, 4, 1, 6, 9},总和 = 24; 输出:12、3、9 解释:存在一个三元组(12、3 和 9) 在总和为 24 的数组中。
输入:数组 = {1, 2, 3, 4, 5},总和 = 9 输出:5、3、1 解释:存在一个三元组(5、3 和 1) 在总和为 9 的数组中。
通过生成所有三元组来求数组中的三元组和 (3sum):
一个简单的方法是生成所有可能的三元组并将每个三元组的总和与给定值进行比较。以下代码使用三层嵌套循环实现这个简单的方法。
分步方法:
- 给定一个长度为 n 的数组 和 总和 s
- 创建三个嵌套循环,第一个循环从开始到结束(循环计数器 i),第二个循环从 i+1 运行到结束(循环计数器 j),第三个循环从 j+1 运行到结束(循环计数器 k)
- 这些循环的计数器代表三元组的 3 个元素的索引。
- 求第 i、j、k 个元素的和。如果总和等于给定总和。打印三元组并中断。
- 如果不存在三元组,则打印不存在三元组。
下面是上述方法的实现:
C++
#include <bits/stdc++.h>
using namespace std;
// returns true if there is triplet with sum equal
// to 'sum' present in A[]. Also, prints the triplet
bool find3Numbers(int A[], int arr_size, int sum)
{
// Fix the first element as A[i]
for (int i = 0; i < arr_size - 2; i++)
{
// Fix the second element as A[j]
for (int j = i + 1; j < arr_size - 1; j++)
{
// Now look for the third number
for (int k = j + 1; k < arr_size; k++)
{
if (A[i] + A[j] + A[k] == sum)
{
cout << "Triplet is " << A[i] <<
", " << A[j] << ", " << A[k];
return true;
}
}
}
}
// If we reach here, then no triplet was found
return false;
}
/* Driver code */
int main()
{
int A[] = { 1, 4, 45, 6, 10, 8 };
int sum = 22;
int arr_size = sizeof(A) / sizeof(A[0]);
find3Numbers(A, arr_size, sum);
return 0;
}
C
#include <stdio.h>
// returns true if there is triplet with sum equal
// to 'sum' present in A[]. Also, prints the triplet
bool find3Numbers(int A[], int arr_size, int sum)
{
int l, r;
// Fix the first element as A[i]
for (int i = 0; i < arr_size - 2; i++) {
// Fix the second element as A[j]
for (int j = i + 1; j < arr_size - 1; j++) {
// Now look for the third number
for (int k = j + 1; k < arr_size; k++) {
if (A[i] + A[j] + A[k] == sum) {
printf("Triplet is %d, %d, %d",
A[i], A[j], A[k]);
return true;
}
}
}
}
// If we reach here, then no triplet was found
return false;
}
/* Driver program to test above function */
int main()
{
int A[] = { 1, 4, 45, 6, 10, 8 };
int sum = 22;
int arr_size = sizeof(A) / sizeof(A[0]);
find3Numbers(A, arr_size, sum);
return 0;
}
Java
// Java program to find a triplet
class FindTriplet {
// returns true if there is triplet with sum equal
// to 'sum' present in A[]. Also, prints the triplet
boolean find3Numbers(int A[], int arr_size, int sum)
{
int l, r;
// Fix the first element as A[i]
for (int i = 0; i < arr_size - 2; i++) {
// Fix the second element as A[j]
for (int j = i + 1; j < arr_size - 1; j++) {
// Now look for the third number
for (int k = j + 1; k < arr_size; k++) {
if (A[i] + A[j] + A[k] == sum) {
System.out.print("Triplet is " + A[i] + ", " + A[j] + ", " + A[k]);
return true;
}
}
}
}
// If we reach here, then no triplet was found
return false;
}
// Driver program to test above functions
public static void main(String[] args)
{
FindTriplet triplet = new FindTriplet();
int A[] = { 1, 4, 45, 6, 10, 8 };
int sum = 22;
int arr_size = A.length;
triplet.find3Numbers(A, arr_size, sum);
}
}
Python
# Python3 program to find a triplet
# that sum to a given value
# returns true if there is triplet with
# sum equal to 'sum' present in A[].
# Also, prints the triplet
def find3Numbers(A, arr_size, sum):
# Fix the first element as A[i]
for i in range( 0, arr_size-2):
# Fix the second element as A[j]
for j in range(i + 1, arr_size-1):
# Now look for the third number
for k in range(j + 1, arr_size):
if A[i] + A[j] + A[k] == sum:
print("Triplet is", A[i],
", ", A[j], ", ", A[k])
return True
# If we reach here, then no
# triplet was found
return False
# Driver program to test above function
A = [1, 4, 45, 6, 10, 8]
sum = 22
arr_size = len(A)
find3Numbers(A, arr_size, sum)
C#
// C# program to find a triplet
// that sum to a given value
using System;
class GFG {
// returns true if there is
// triplet with sum equal
// to 'sum' present in A[].
// Also, prints the triplet
static bool find3Numbers(int[] A,
int arr_size,
int sum)
{
// Fix the first
// element as A[i]
for (int i = 0;
i < arr_size - 2; i++) {
// Fix the second
// element as A[j]
for (int j = i + 1;
j < arr_size - 1; j++) {
// Now look for
// the third number
for (int k = j + 1;
k < arr_size; k++) {
if (A[i] + A[j] + A[k] == sum) {
Console.WriteLine("Triplet is " + A[i] + ", " + A[j] + ", " + A[k]);
return true;
}
}
}
}
// If we reach here,
// then no triplet was found
return false;
}
// Driver Code
static public void Main()
{
int[] A = { 1, 4, 45, 6, 10, 8 };
int sum = 22;
int arr_size = A.Length;
find3Numbers(A, arr_size, sum);
}
}
Javascript
<script>
// Javascript program to find a triplet
// returns true if there is triplet with sum equal
// to 'sum' present in A[]. Also, prints the triplet
function find3Numbers(A, arr_size, sum)
{
let l, r;
// Fix the first element as A[i]
for (let i = 0; i < arr_size - 2; i++)
{
// Fix the second element as A[j]
for (let j = i + 1; j < arr_size - 1; j++)
{
// Now look for the third number
for (let k = j + 1; k < arr_size; k++)
{
if (A[i] + A[j] + A[k] == sum)
{
document.write("Triplet is " + A[i] +
", " + A[j] + ", " + A[k]);
return true;
}
}
}
}
// If we reach here, then no triplet was found
return false;
}
/* Driver code */
let A = [ 1, 4, 45, 6, 10, 8 ];
let sum = 22;
let arr_size = A.length;
find3Numbers(A, arr_size, sum);
</script>
PHP
<?php
// PHP program to find a triplet
// that sum to a given value
// returns true if there is
// triplet with sum equal to
// 'sum' present in A[].
// Also, prints the triplet
function find3Numbers($A, $arr_size, $sum)
{
$l; $r;
// Fix the first
// element as A[i]
for ($i = 0;
$i < $arr_size - 2; $i++)
{
// Fix the second
// element as A[j]
for ($j = $i + 1;
$j < $arr_size - 1; $j++)
{
// Now look for the
// third number
for ($k = $j + 1;
$k < $arr_size; $k++)
{
if ($A[$i] + $A[$j] +
$A[$k] == $sum)
{
echo "Triplet is", " ", $A[$i],
", ", $A[$j],
", ", $A[$k];
return true;
}
}
}
}
// If we reach here, then
// no triplet was found
return false;
}
// Driver Code
$A = array(1, 4, 45,
6, 10, 8);
$sum = 22;
$arr_size = sizeof($A);
find3Numbers($A, $arr_size, $sum);
?>
输出
Triplet is 4, 10, 8
复杂度分析:
- 时间复杂度:O(n^3),有3个嵌套循环遍历数组,所以时间复杂度为O(n^3)
- 辅助空间:O(1),因为不需要额外的空间。
使用两指针技术计算数组中的三元组和 (3sum):
通过对数组进行排序可以提高算法的效率。遍历数组并固定三元组的第一个元素,使用双指针算法来查找是否存在一对总和等于 x – array[i] 的指针对。两指针算法需要线性时间,因此它比三层嵌套循环更好。
分步方法:
-
对给定的数组进行排序。
-
循环数组并修复可能的三元组的第一个元素,arr[i]。
-
然后固定两个指针,一个在 i + 1 处,另一个在 n – 1 处。然后看一下总和,
- 如果总和小于所需总和,则递增第一个指针。
- 否则,如果总和较大,则减少结束指针以减少总和。
- 否则,如果两个指针处的元素之和等于给定的和,则打印三元组并中断。
下面是上述方法的实现:
C++
// C++ program to find a triplet
#include <bits/stdc++.h>
using namespace std;
// returns true if there is triplet with sum equal
// to 'sum' present in A[]. Also, prints the triplet
bool find3Numbers(int A[], int arr_size, int sum)
{
int l, r;
/* Sort the elements */
sort(A, A + arr_size);
/* Now fix the first element one by one and find the
other two elements */
for (int i = 0; i < arr_size - 2; i++) {
// To find the other two elements, start two index
// variables from two corners of the array and move
// them toward each other
l = i + 1; // index of the first element in the
// remaining elements
r = arr_size - 1; // index of the last element
while (l < r) {
if (A[i] + A[l] + A[r] == sum) {
printf("Triplet is %d, %d, %d", A[i], A[l],A[r]);
return true;
}
else if (A[i] + A[l] + A[r] < sum)
l++;
else // A[i] + A[l] + A[r] > sum
r--;
}
}
// If we reach here, then no triplet was found
return false;
}
/* Driver program to test above function */
int main()
{
int A[] = { 1, 4, 45, 6, 10, 8 };
int sum = 22;
int arr_size = sizeof(A) / sizeof(A[0]);
find3Numbers(A, arr_size, sum);
return 0;
}
C
// C program to find a triplet
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int cmpfunc(const void* a, const void* b)
{
return (*(int*)a - *(int*)b);
}
// returns true if there is triplet with sum equal
// to 'sum' present in A[]. Also, prints the triplet
bool find3Numbers(int A[], int arr_size, int sum)
{
int l, r;
/* Sort the elements */
qsort(A, arr_size, sizeof(int), cmpfunc);
/* Now fix the first element one by one and find the
other two elements */
for (int i = 0; i < arr_size - 2; i++)
{
// To find the other two elements, start two index
// variables from two corners of the array and move
// them toward each other
l = i + 1; // index of the first element in the
// remaining elements
r = arr_size - 1; // index of the last element
while (l < r) {
if (A[i] + A[l] + A[r] == sum) {
printf("Triplet is %d, %d, %d", A[i], A[l],
A[r]);
return true;
}
else if (A[i] + A[l] + A[r] < sum)
l++;
else // A[i] + A[l] + A[r] > sum
r--;
}
}
// If we reach here, then no triplet was found
return false;
}
/* Driver program to test above function */
int main()
{
int A[] = { 1, 4, 45, 6, 10, 8 };
int sum = 22;
int arr_size = sizeof(A) / sizeof(A[0]);
find3Numbers(A, arr_size, sum);
return 0;
}
Java
// Java program to find a triplet
class FindTriplet {
// returns true if there is triplet with sum equal
// to 'sum' present in A[]. Also, prints the triplet
boolean find3Numbers(int A[], int arr_size, int sum)
{
int l, r;
/* Sort the elements */
quickSort(A, 0, arr_size - 1);
/* Now fix the first element one by one and find the
other two elements */
for (int i = 0; i < arr_size - 2; i++) {
// To find the other two elements, start two
// index variables from two corners of the array
// and move them toward each other
l = i + 1; // index of the first element in the
// remaining elements
r = arr_size - 1; // index of the last element
while (l < r) {
if (A[i] + A[l] + A[r] == sum) {
System.out.print("Triplet is " + A[i] + ", " + A[l] + ", " + A[r]);
return true;
}
else if (A[i] + A[l] + A[r] < sum)
l++;
else // A[i] + A[l] + A[r] > sum
r--;
}
}
// If we reach here, then no triplet was found
return false;
}
int partition(int A[], int si, int ei)
{
int x = A[ei];
int i = (si - 1);
int j;
for (j = si; j <= ei - 1; j++) {
if (A[j] <= x) {
i++;
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}
int temp = A[i + 1];
A[i + 1] = A[ei];
A[ei] = temp;
return (i + 1);
}
/* Implementation of Quick Sort
A[] --> Array to be sorted
si --> Starting index
ei --> Ending index
*/
void quickSort(int A[], int si, int ei)
{
int pi;
/* Partitioning index */
if (si < ei) {
pi = partition(A, si, ei);
quickSort(A, si, pi - 1);
quickSort(A, pi + 1, ei);
}
}
// Driver program to test above functions
public static void main(String[] args)
{
FindTriplet triplet = new FindTriplet();
int A[] = { 1, 4, 45, 6, 10, 8 };
int sum = 22;
int arr_size = A.length;
triplet.find3Numbers(A, arr_size, sum);
}
}
Python
# Python3 program to find a triplet
# returns true if there is triplet
# with sum equal to 'sum' present
# in A[]. Also, prints the triplet
def find3Numbers(A, arr_size, sum):
# Sort the elements
A.sort()
# Now fix the first element
# one by one and find the
# other two elements
for i in range(0, arr_size-2):
# To find the other two elements,
# start two index variables from
# two corners of the array and
# move them toward each other
# index of the first element
# in the remaining elements
l = i + 1
# index of the last element
r = arr_size-1
while (l < r):
if( A[i] + A[l] + A[r] == sum):
print("Triplet is", A[i],
', ', A[l], ', ', A[r]);
return True
elif (A[i] + A[l] + A[r] < sum):
l += 1
else: # A[i] + A[l] + A[r] > sum
r -= 1
# If we reach here, then
# no triplet was found
return False
# Driver program to test above function
A = [1, 4, 45, 6, 10, 8]
sum = 22
arr_size = len(A)
find3Numbers(A, arr_size, sum)
C#
// C# program to find a triplet
using System;
class GFG {
// returns true if there is triplet
// with sum equal to 'sum' present
// in A[]. Also, prints the triplet
bool find3Numbers(int[] A, int arr_size,
int sum)
{
int l, r;
/* Sort the elements */
quickSort(A, 0, arr_size - 1);
/* Now fix the first element
one by one and find the
other two elements */
for (int i = 0; i < arr_size - 2; i++) {
// To find the other two elements,
// start two index variables from
// two corners of the array and
// move them toward each other
l = i + 1; // index of the first element
// in the remaining elements
r = arr_size - 1; // index of the last element
while (l < r) {
if (A[i] + A[l] + A[r] == sum) {
Console.Write("Triplet is " + A[i] + ", " + A[l] + ", " + A[r]);
return true;
}
else if (A[i] + A[l] + A[r] < sum)
l++;
else // A[i] + A[l] + A[r] > sum
r--;
}
}
// If we reach here, then
// no triplet was found
return false;
}
int partition(int[] A, int si, int ei)
{
int x = A[ei];
int i = (si - 1);
int j;
for (j = si; j <= ei - 1; j++) {
if (A[j] <= x) {
i++;
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}
int temp1 = A[i + 1];
A[i + 1] = A[ei];
A[ei] = temp1;
return (i + 1);
}
/* Implementation of Quick Sort
A[] --> Array to be sorted
si --> Starting index
ei --> Ending index
*/
void quickSort(int[] A, int si, int ei)
{
int pi;
/* Partitioning index */
if (si < ei) {
pi = partition(A, si, ei);
quickSort(A, si, pi - 1);
quickSort(A, pi + 1, ei);
}
}
// Driver Code
static void Main()
{
GFG triplet = new GFG();
int[] A = new int[] { 1, 4, 45, 6, 10, 8 };
int sum = 22;
int arr_size = A.Length;
triplet.find3Numbers(A, arr_size, sum);
}
}
Javascript
<script>
// Javascript program to find a triplet
// returns true if there is triplet with sum equal
// to 'sum' present in A[]. Also, prints the triplet
function find3Numbers(A, arr_size, sum)
{
let l, r;
/* Sort the elements */
A.sort((a,b) => a-b);
/* Now fix the first element one
by one and find the
other two elements */
for (let i = 0; i < arr_size - 2; i++) {
// To find the other two
// elements, start two index
// variables from two corners of
// the array and move
// them toward each other
// index of the first element in the
l = i + 1;
// remaining elements
// index of the last element
r = arr_size - 1;
while (l < r) {
if (A[i] + A[l] + A[r] == sum)
{
document.write("Triplet is " + A[i] + ", "
+ A[l] + ", " + A[r]);
return true;
}
else if (A[i] + A[l] + A[r] < sum)
l++;
else // A[i] + A[l] + A[r] > sum
r--;
}
}
// If we reach here, then no triplet was found
return false;
}
/* Driver program to test above function */
let A = [ 1, 4, 45, 6, 10, 8 ];
let sum = 22;
let arr_size = A.length;
find3Numbers(A, arr_size, sum);
</script>
PHP
<?php
// PHP program to find a triplet
// returns true if there is
// triplet with sum equal to
// 'sum' present in A[]. Also,
// prints the triplet
function find3Numbers($A, $arr_size, $sum)
{
$l; $r;
/* Sort the elements */
sort($A);
/* Now fix the first element
one by one and find the
other two elements */
for ($i = 0; $i < $arr_size - 2; $i++)
{
// To find the other two elements,
// start two index variables from
// two corners of the array and
// move them toward each other
$l = $i + 1; // index of the first element
// in the remaining elements
// index of the last element
$r = $arr_size - 1;
while ($l < $r)
{
if ($A[$i] + $A[$l] +
$A[$r] == $sum)
{
echo "Triplet is ", $A[$i], " ",
$A[$l], " ",
$A[$r], "\n";
return true;
}
else if ($A[$i] + $A[$l] +
$A[$r] < $sum)
$l++;
else // A[i] + A[l] + A[r] > sum
$r--;
}
}
// If we reach here, then
// no triplet was found
return false;
}
// Driver Code
$A = array (1, 4, 45, 6, 10, 8);
$sum = 22;
$arr_size = sizeof($A);
find3Numbers($A, $arr_size, $sum);
?>
输出
Triplet is 4, 8, 10
复杂度分析:
- 时间复杂度:O(N^2),遍历数组的嵌套循环只有两次,所以时间复杂度为O(n^2)。两指针算法需要 O(n) 时间,并且可以使用另一个嵌套遍历来固定第一个元素。
- 辅助空间:O(1),因为不需要额外的空间。
使用哈希计算数组中的三元组和 (3sum):
这种方法使用额外的空间,但比两指针方法更简单。运行两个循环,外循环从开始到结束,内循环从 i+1 到结束。创建一个 hashmap 或 set 来存储 i+1 到 n-1 之间的元素。因此,如果给定的总和为 x,则检查集合中是否存在等于 x – arr[i] – arr[j] 的数字。如果是,则打印三元组。
分步方法:
- 迭代数组,固定三元组的第一个元素 (A[i])。
- 对于每个 A[i],使用 Hashmap 存储完成所需总和 (sum – A[i]) 的潜在第二个元素。
- 在嵌套循环内,检查当前元素 (A[j]) 与所需总和 (sum – A[i]) 之间的差异是否存在于 Hashmap 中。如果是,则找到三元组,然后打印它。
- 如果在整个数组中没有找到三元组,则函数返回 false。
下面是上述方法的实现:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find a triplet with a given sum in an array
bool find3Numbers(int A[], int arr_size, int sum)
{
// Fix the first element as A[i]
for (int i = 0; i < arr_size - 2; i++) {
// Create a set to store potential second elements
// that complement the desired sum
unordered_set<int> s;
// Calculate the current sum needed to reach the
// target sum
int curr_sum = sum - A[i];
// Iterate through the subarray A[i+1..n-1] to find
// a pair with the required sum
for (int j = i + 1; j < arr_size; j++) {
// Calculate the required value for the second
// element
int required_value = curr_sum - A[j];
// Check if the required value is present in the
// set
if (s.find(required_value) != s.end()) {
// Triplet is found; print the triplet
// elements
printf("Triplet is %d, %d, %d", A[i], A[j],
required_value);
return true;
}
// Add the current element to the set for future
// complement checks
s.insert(A[j]);
}
}
// If no triplet is found, return false
return false;
}
/* Driver program to test above function */
int main()
{
int A[] = { 1, 4, 45, 6, 10, 8 };
int sum = 22;
int arr_size = sizeof(A) / sizeof(A[0]);
// Call the find3Numbers function to find and print the
// triplet, if it exists
find3Numbers(A, arr_size, sum);
return 0;
}
Java
import java.util.HashSet;
public class TripletSumFinder {
// Function to find a triplet with a given sum in an
// array
public static boolean
find3Numbers(int[] A, int arr_size, int sum)
{
// Fix the first element as A[i]
for (int i = 0; i < arr_size - 2; i++) {
// Create a HashSet to store potential second
// elements that complement the desired sum
HashSet<Integer> s = new HashSet<>();
// Calculate the current sum needed to reach the
// target sum
int curr_sum = sum - A[i];
// Iterate through the subarray A[i+1..n-1] to
// find a pair with the required sum
for (int j = i + 1; j < arr_size; j++) {
// Calculate the required value for the
// second element
int required_value = curr_sum - A[j];
// Check if the required value is present in
// the HashSet
if (s.contains(required_value)) {
// Triplet is found; print the triplet
// elements
System.out.println("Triplet is " + A[i]
+ ", " + A[j] + ", "
+ required_value);
return true;
}
// Add the current element to the HashSet
// for future complement checks
s.add(A[j]);
}
}
// If no triplet is found, return false
return false;
}
public static void main(String[] args)
{
int[] A = { 1, 4, 45, 6, 10, 8 };
int sum = 22;
int arr_size = A.length;
// Call the find3Numbers function to find and print
// the triplet, if it exists
if (!find3Numbers(A, arr_size, sum)) {
System.out.println(
"No triplet found with the given sum.");
}
}
}
Python
# Function to find a triplet with a given sum in an array
def find3Numbers(arr, sum):
# Fix the first element as arr[i]
for i in range(len(arr) - 2):
# Create a set to store potential second elements that complement the desired sum
s = set()
# Calculate the current sum needed to reach the target sum
curr_sum = sum - arr[i]
# Iterate through the subarray arr[i+1:]
for j in range(i + 1, len(arr)):
# Calculate the required value for the second element
required_value = curr_sum - arr[j]
# Check if the required value is present in the set
if required_value in s:
# Triplet is found; print the triplet elements
print(f"Triplet is {arr[i]}, {arr[j]}, {required_value}")
return True
# Add the current element to the set for future complement checks
s.add(arr[j])
# If no triplet is found, return False
return False
# Driver program to test above function
if __name__ == "__main__":
arr = [1, 4, 45, 6, 10, 8]
target_sum = 22
# Call the find3Numbers function to find and print the triplet, if it exists
if not find3Numbers(arr, target_sum):
print("No triplet found.")
C#
using System;
using System.Collections.Generic;
class Program {
// Function to find a triplet with a given sum in an
// array
static bool Find3Numbers(int[] arr, int sum)
{
// Fix the first element as arr[i]
for (int i = 0; i < arr.Length - 2; i++) {
// Create a HashSet to store potential second
// elements that complement the desired sum
HashSet<int> s = new HashSet<int>();
// Calculate the current sum needed to reach the
// target sum
int curr_sum = sum - arr[i];
// Iterate through the subarray arr[i+1:]
for (int j = i + 1; j < arr.Length; j++) {
// Calculate the required value for the
// second element
int required_value = curr_sum - arr[j];
// Check if the required value is present in
// the HashSet
if (s.Contains(required_value)) {
// Triplet is found; print the triplet
// elements
Console.WriteLine("Triplet is " + arr[i]
+ ", " + arr[j] + ", "
+ required_value);
return true;
}
// Add the current element to the HashSet
// for future complement checks
s.Add(arr[j]);
}
}
// If no triplet is found, return false
return false;
}
// Driver program to test the Find3Numbers function
static void Main()
{
int[] arr = { 1, 4, 45, 6, 10, 8 };
int target_sum = 22;
// Call the Find3Numbers function to find and print
// the triplet, if it exists
if (!Find3Numbers(arr, target_sum)) {
Console.WriteLine("No triplet found.");
}
}
}
Javascript
function find3Numbers(A, sum) {
// Fix the first element as A[i]
for (let i = 0; i < A.length - 2; i++) {
// Create a Set to store potential second elements that complement the desired sum
const s = new Set();
// Calculate the current sum needed to reach the target sum
const currSum = sum - A[i];
// Iterate through the subarray A[i+1..n-1] to find a pair with the required sum
for (let j = i + 1; j < A.length; j++) {
// Calculate the required value for the second element
const requiredValue = currSum - A[j];
// Check if the required value is present in the Set
if (s.has(requiredValue)) {
// Triplet is found; print the triplet elements
console.log(`Triplet is ${A[i]}, ${A[j]}, ${requiredValue}`);
return true;
}
// Add the current element to the Set for future complement checks
s.add(A[j]);
}
}
// If no triplet is found, return false
return false;
}
function main() {
const A = [1, 4, 45, 6, 10, 8];
const sum = 22;
// Call the find3Numbers function to find and print the triplet, if it exists
if (!find3Numbers(A, sum)) {
console.log("No triplet found with the given sum.");
}
}
// Call the main function to start the program
main();
输出
Triplet is 4, 8, 10
时间复杂度:O(N^2) 辅助空间:O(N),因为已占用 n 个额外空间