logo

Trojna vsota v nizu (3 vsota)

Podana matrika prihod [] velikosti n in celo število X . Ugotovite, ali je v matriki trojček, ki sešteje dano celo število X .

Primeri:



Vnos: matrika = {12, 3, 4, 1, 6, 9}, vsota = 24;
Izhod: 12, 3, 9
Pojasnilo: Prisoten je trojček (12, 3 in 9).
v matriki, katere vsota je 24.

Vnos: niz = {1, 2, 3, 4, 5}, vsota = 9
Izhod: 5, 3, 1
Pojasnilo: Prisoten je trojček (5, 3 in 1).
v matriki, katere vsota je 9.

Priporočena praksa Vadite trojno vsoto v matriki. Poskusite!

Trojna vsota v nizu (3 vsota) z generiranjem vseh trojčkov:

Preprosta metoda je generiranje vseh možnih trojčkov in primerjava vsote vsakega trojčka z dano vrednostjo. Naslednja koda izvaja to preprosto metodo z uporabo treh ugnezdenih zank.



Pristop po korakih:

  • Podano je polje dolžine n in vsota s
  • Ustvarite tri ugnezdene zanke, prva zanka teče od začetka do konca (števec zank i), druga zanka teče od i+1 do konca (števec zanke j) in tretja zanka teče od j+1 do konca (števec zanke k)
  • Števec teh zank predstavlja indeks 3 elementi trojčkov.
  • Poiščite vsoto i-tega, j-tega in k-tega elementa. Če je vsota enaka dani vsoti. Natisni trojček in prelomi.
  • Če trojčka ni, potem izpiši, da trojček ne obstaja.

Spodaj je izvedba zgornjega pristopa:

C++






#include> 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 { // Fix the second element as A[j] for (int j = i + 1; j { // Now look for the third number for (int k = j + 1; 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; } // This is code is contributed by rathbhupendra>

>

>

C




#include> // 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 // Fix the second element as A[j] for (int j = i + 1; j // Now look for the third number for (int k = j + 1; 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; }>

>

fmoviez

>

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 2; i++) { // Fix the second element as A[j] for (int j = i + 1; j 1; j++) { // Now look for the third number for (int k = j + 1; 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); } }>

>

>

Python3




# 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>)> # This code is contributed by Smitha Dinesh Semwal>

>

>

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 // Fix the second // element as A[j] for (int j = i + 1; j // Now look for // the third number for (int k = j + 1; 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); } } // This code is contributed by m_kit>

>

>

Javascript




> // 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 { // Fix the second element as A[j] for (let j = i + 1; j { // Now look for the third number for (let k = j + 1; 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); // This code is contributed by Mayank Tyagi>

>

>

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); // This code is contributed by ajit ?>>

>

>

Izhod

Triplet is 4, 10, 8>

Analiza kompleksnosti:

  • Časovna zapletenost: O(n3), obstajajo tri ugnezdene zanke, ki prečkajo matriko, zato je časovna kompleksnost O(n^3)
  • Pomožni prostor: O(1), ker ni potreben dodaten prostor.

Trojna vsota v nizu (3 vsota) uporabo Tehnika dveh kazalcev :

Z razvrščanjem matrike je mogoče izboljšati učinkovitost algoritma. Ta učinkovit pristop uporablja tehnika dveh točk . Prečkajte niz in popravite prvi element trojčka. Zdaj uporabite algoritem dveh kazalcev, da ugotovite, ali obstaja par, katerega vsota je enaka x – polje [i] . Algoritem dveh kazalcev zahteva linearni čas, zato je boljši od ugnezdene zanke.

Pristop po korakih:

  • Razvrsti podano matriko.
  • Pojdite čez matriko in popravite prvi element možnega trojčka, pride[i] .
  • Nato popravite dva kazalca, enega na i + 1 in drugi pri n – 1 . In poglej vsoto,
    • Če je vsota manjša od zahtevane vsote, povečaj prvi kazalec.
    • V nasprotnem primeru, če je vsota večja, zmanjšajte končni kazalec, da zmanjšate vsoto.
    • V nasprotnem primeru, če je vsota elementov v dveh točkah enaka dani vsoti, potem natisni trojček in prelomi.

Spodaj je izvedba zgornjega pristopa:

C++




// C++ program to find a triplet> #include> 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 // 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 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] l++; else // A[i] + A[l] + A[r]>vsota r--; } } // Če pridemo sem, potem ni bil najden trojček return false; } /* Program gonilnika za testiranje zgornje funkcije */ int main() { int A[] = { 1, 4, 45, 6, 10, 8 }; int vsota = 22; int arr_size = sizeof(A) / sizeof(A[0]); poišči3števila(A, arr_size, vsota); vrni 0; } // To kodo je prispeval Aditya Kumar (adityakumar129)>

>

>

C




// C program to find a triplet> #include> #include> #include> 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 { // 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 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] l++; else // A[i] + A[l] + A[r]>vsota r--; } } // Če pridemo sem, potem ni bil najden trojček return false; } /* Program gonilnika za testiranje zgornje funkcije */ int main() { int A[] = { 1, 4, 45, 6, 10, 8 }; int vsota = 22; int arr_size = sizeof(A) / sizeof(A[0]); poišči3števila(A, arr_size, vsota); vrni 0; } // To kodo je prispeval Aditya Kumar (adityakumar129)>

>

>

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 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 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] l++; else // A[i] + A[l] + A[r]>vsota r--; } } // Če pridemo sem, potem ni bil najden trojček return false; } int particija(int A[], int si, int ei) { int x = A[ei]; int i = (si - 1); int j; za (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[] -->Matrika za razvrščanje si --> Začetni indeks ei --> Končni indeks */ void quickSort(int A[], int si, int ei) { int pi; /* Indeks particioniranja */ if (si pi = particija(A, si, ei); quickSort(A, si, pi - 1); quickSort(A, pi + 1, ei); } } // Program gonilnika za testiranje zgoraj statični public(String[] args) { FindTriplet = new FindTriplet(); int arr_size = A. dolžina; triplet.find3Numbers(A, arr_size, sum); }>

>

>

Python3




# 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 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] vsota r -= 1 # Če pridemo sem, potem # trojček ni bil najden vrni False # Program gonilnika za preizkus zgornje funkcije A = [1, 4, 45, 6, 10, 8] vsota = 22 arr_size = len(A) find3Numbers(A, arr_size, sum) # To je prispeval Smitha Dinesh Semwal>

>

>

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 // 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 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] l++; else // A[i] + A[l] + A[r]>vsota r--; } } // Če pridemo sem, potem // ni bil najden trojček return false; } int particija(int[] A, int si, int ei) { int x = A[ei]; int i = (si - 1); int j; za (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[] -->Matrika za razvrščanje si --> Začetni indeks ei --> Končni indeks */ void quickSort(int[] A, int si, int ei) { int pi; /* Indeks particioniranja */ if (si pi = particija(A, si, ei); quickSort(A, si, pi - 1); quickSort(A, pi + 1, ei); } } // Statična praznina kode gonilnika Main() {GFG triplet(); int[] A = new int[] {1, 4, 45, 10, 8}; int arr_size = A.Length.find3Numbers (A, arr_size, sum); // To kodo je prispeval mits>

>

>

Javascript




> // 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 // 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 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] l++; else // A[i] + A[l] + A[r]>vsota r--; } } // Če pridemo sem, potem ni bil najden trojček return false; } /* Program gonilnika za testiranje zgornje funkcije */ let A = [ 1, 4, 45, 6, 10, 8 ]; naj bo vsota = 22; naj arr_size = A.length; poišči3števila(A, arr_size, vsota); // To kodo je prispeval Mayank Tyagi>

>

>

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], ' '; return true; } else if ($A[$i] + $A[$l] + $A[$r] <$sum) $l++; else // A[i] + A[l] + A[r]>vsota $r--; } } // Če pridemo sem, potem // ni bil najden trojček return false; } // Koda gonilnika $A = polje (1, 4, 45, 6, 10, 8); $vsota = 22; $arr_size = sizeof($A); poišči3števila($A, $arr_size, $sum); // To kodo je prispeval ajit ?>>

>

>

Izhod

Triplet is 4, 8, 10>

Analiza kompleksnosti:

  • Časovna zahtevnost: O(N^2), Obstajata samo dve ugnezdeni zanki, ki prečkata matriko, zato je časovna kompleksnost O(n^2). Algoritem dveh kazalcev potrebuje O(n) časa in prvi element je mogoče popraviti z drugim ugnezdenim prehodom.
  • Pomožni prostor: O(1), ker ni potreben dodaten prostor.

Trojna vsota v nizu (3 vsota) uporabo Zgoščevanje :

Ta pristop uporablja dodaten prostor, vendar je enostavnejši od pristopa z dvema točkama. Zaženite dve zanki zunanjo zanko od začetka do konca in notranjo zanko od i+1 Na konec. Ustvarite hashmap ali nastavite za shranjevanje vmesnih elementov i+1 do n-1 . Torej, če je dana vsota x, preveri, ali je v nizu število, ki je enako x – arr[i] – arr[j] . Če da, izpiši trojček.

Pristop po korakih:

  • Iterirajte skozi matriko in popravite prvi element ( A[i] ) za trojček.
  • Za vsakogar A[i] , uporabite Hashmap za shranjevanje potencialnih drugih elementov, ki dopolnijo želeno vsoto (vsota – A[i]) .
  • Znotraj ugnezdene zanke preverite, ali je razlika med trenutnim elementom ( A[j] ) in želeno vsoto ( vsota – A[i] ) je prisoten v Hashmapu. Če je, je najden trojček, nato ga natisnite.
  • Če v celotnem nizu ni najdenega trojčka, se funkcija vrne lažno .

Spodaj je izvedba zgornjega pristopa:

C++




#include> 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 // Create a set to store potential second elements // that complement the desired sum unordered_set s; // Izračunajte trenutno vsoto, potrebno za doseganje // ciljne vsote int curr_sum = vsota - A[i]; // Iteracija skozi podmatriko A[i+1..n-1], da bi našli // par z zahtevano vsoto za (int j = i + 1; j // Izračunajte zahtevano vrednost za drugi // element int required_value = curr_sum - A[j]; // Preverite, ali je zahtevana vrednost prisotna v // nizu if (s.find(required_value) != s.end()) { // Triplet je najden; / elements printf('Triplet je %d, %d, %d', A[i], A[j], return true; } // Dodajte trenutni element v nabor za prihodnje dopolnjevanje preveri s.insert(A[j]); // Če ni najden trojček, vrni false return false } /* Program gonilnika za testiranje zgornje funkcije */ int main() { int A[] = { 1, 4, 45, 6, 10, 8 }; int arr_size = sizeof(A) / sizeof(A[0]); // Pokliči funkcijo find3Numbers, da najde in natisne trojček //, če obstaja 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 2; i++) { // Create a HashSet to store potential second // elements that complement the desired sum HashSet 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 // 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.'); } } }>

>

>

Python3




# 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 // Create a HashSet to store potential second // elements that complement the desired sum HashSet s = nov HashSet (); // Izračunajte trenutno vsoto, potrebno za doseganje // ciljne vsote int curr_sum = vsota - arr[i]; // Iteracija skozi podmatriko arr[i+1:] for (int j = i + 1; j // Izračunaj zahtevano vrednost za // drugi element int required_value = curr_sum - arr[j]; // Preverite, ali zahtevana vrednost je prisotna v // HashSet if (s.Contains(required_value)) { // Triplet je najden; natisni trojček // elements Console.WriteLine('Triplet je ' + arr[i] + ', ' + arr[j] + ' + required_value; // Dodajanje trenutnega elementa v HashSet // za preverjanje komplementa s.Add(arr[j]); Če ni najden noben trojček, vrni false; } // Program gonilnika za testiranje funkcije Find3Numbers static void () { int [] arr = { 1, 4, 45, 6, 10, 8 }; int target_sum = 22 ; // Pokličite funkcijo Find3Numbers, da poiščete in izpišete // trojček, če obstaja (!Find3Numbers(arr, target_sum)) { Console.WriteLine('Ni najdenega trojčka.'); } } }>

>

>

Javascript




function> find3Numbers(A, sum) {> >// Fix the first element as A[i]> >for> (let i = 0; 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 // 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();>

>

>

Izhod

Triplet is 4, 8, 10>

Časovna zahtevnost: O(N^2)
Pomožni prostor: O(N), ker je bilo zavzetih n dodatnih prostorov

Razlago problema si lahko ogledate na YouTube razpravlja Geeks For Geeks Team.

Lahko se tudi sklicujete to video prisoten na Youtube.
Kako natisniti vse trojčke z dano vsoto?
Refer Poišči vse trojčke z vsoto nič .