Dané pole arr[] velikosti n a celé číslo X . Zjistěte, zda je v poli trojice, která se rovná danému celému číslu X .
Příklady:
Doporučená praxe Triplet Sum in Array Vyzkoušejte to!Vstup: pole = {12, 3, 4, 1, 6, 9}, součet = 24;
Výstup: 12, 3, 9
Vysvětlení: Je přítomna trojice (12, 3 a 9).
v poli, jehož součet je 24.zřetězit java řetězecVstup: pole = {1, 2, 3, 4, 5}, součet = 9
Výstup: 5, 3, 1
Vysvětlení: Je přítomna trojice (5, 3 a 1).
v poli, jehož součet je 9.
Trojitý součet v poli (3 součet) vygenerováním všech trojic:
Jednoduchou metodou je vygenerovat všechny možné triplety a porovnat součet každého tripletu s danou hodnotou. Následující kód implementuje tuto jednoduchou metodu pomocí tří vnořených smyček.
Postup krok za krokem:
- Vzhledem k řadě délek n a částku s
- Vytvořte tři vnořené smyčky, první smyčka běží od začátku do konce (počítadlo smyčky i), druhá smyčka běží od i+1 do konce (počítadlo smyčky j) a třetí smyčka běží od j+1 do konce (počítadlo smyčky k)
- Čítač těchto smyček představuje index 3 prvky trojic.
- Najděte součet i-tého, j-tého a k-tého prvku. Pokud se součet rovná danému součtu. Vytiskněte trojici a přerušte.
- Pokud neexistuje žádná trojice, vytiskněte, že žádná trojice neexistuje.
Níže je uvedena implementace výše uvedeného přístupu:
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; }> |
>
>
Jáva
// 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 ?>> |
>
>Výstup
Triplet is 4, 10, 8>
Analýza složitosti:
- Časová náročnost: Na3), Pole procházejí tři vnořené smyčky, takže časová složitost je O(n^3)
- Pomocný prostor: O(1), protože není potřeba žádný prostor navíc.
Trojitý součet v poli (3 součet) použitím Technika dvou ukazatelů :
Tříděním pole lze zlepšit účinnost algoritmu. Tento efektivní přístup využívá dvoubodová technika . Projděte pole a opravte první prvek trojice. Nyní pomocí algoritmu Two Pointers zjistěte, zda existuje pár, jehož součet je roven x – pole[i] . Algoritmus dvou ukazatelů trvá lineárně, takže je lepší než vnořená smyčka.
Postup krok za krokem:
- Seřaďte dané pole.
- Otočte pole a opravte první prvek možného tripletu, arr[i] .
- Pak opravte dva ukazatele, jeden na i + 1 a druhý na n – 1 . A podívej se na součet,
- Pokud je součet menší než požadovaný součet, zvyšte první ukazatel.
- Jinak, je-li součet větší, snižte součet snížením koncového ukazatele.
- V opačném případě, pokud je součet prvků ve dvou bodech roven danému součtu, vytiskněte trojici a zlomte.
Níže je uvedena implementace výše uvedeného přístupu:
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]>součet r--; } } // Pokud se dostaneme sem, pak nebyla nalezena žádná trojice return false; } /* Program ovladače k otestování výše uvedené funkce */ int main() { int A[] = { 1, 4, 45, 6, 10, 8 }; int součet = 22; int arr_size = sizeof(A) / sizeof(A[0]); najdi3cisla(A, velikost_arru, soucet); návrat 0; } // Tento kód přispěl 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]>součet r--; } } // Pokud se dostaneme sem, pak nebyla nalezena žádná trojice return false; } /* Program ovladače k otestování výše uvedené funkce */ int main() { int A[] = { 1, 4, 45, 6, 10, 8 }; int součet = 22; int arr_size = sizeof(A) / sizeof(A[0]); najdi3cisla(A, velikost_arru, soucet); návrat 0; } // Tento kód přispěl Aditya Kumar (adityakumar129)> |
nový řádek v pythonu
>
>
Jáva
// 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]>součet r--; } } // Pokud se dostaneme sem, pak nebyla nalezena žádná trojice return false; } int partition(int A[], int si, int ei) { int x = A[ei]; int i = (si - 1); int j; pro (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[] -->Pole k seřazení si --> Počáteční index ei --> Koncový index */ void quickSort(int A[], int si, int ei) { int pi; /* Index rozdělení */ if (si pi = partition(A, si, ei); quickSort(A, si, pi - 1); quickSort(A, pi + 1, ei); } } // Program ovladače k testování výše uvedené funkce public static main(String[] args) { FindTriplet triplet = new FindTriplet() int A[] = { 1, 4, 45, 6, 10, 8 }; int arr_size = A; délka; najdi3čísla(A, velikost_arr, součet); |
>
# 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]součet r -= 1 # Pokud se dostaneme sem, pak # nebyla nalezena žádná trojice return False # Program ovladače k testování výše uvedené funkce A = [1, 4, 45, 6, 10, 8] součet = 22 arr_size = len(A) find3Numbers(A, arr_size, sum) # Přispěl 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]>součet r--; } } // Pokud se dostaneme sem, pak // nebyla nalezena žádná trojice return false; } int partition(int[] A, int si, int ei) { int x = A[ei]; int i = (si - 1); int j; pro (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[] -->Pole k seřazení si --> Počáteční index ei --> Koncový index */ void quickSort(int[] A, int si, int ei) { int pi; /* Index rozdělení */ if (si pi = partition(A, si, ei); quickSort(A, si, pi - 1); quickSort(A, pi + 1, ei); } } // Kód ovladače statický void Main() { GFG triplet = new GFG(] A = new int[] { 1, 4, 45, 6, 10, 8 }; int arr_velikost = A.Length (A, arr_size, sum, sum } } // Tento kód přispěl 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]>součet r--; } } // Pokud se dostaneme sem, pak nebyla nalezena žádná trojice return false; } /* Program ovladače k otestování výše uvedené funkce */ nechť A = [ 1, 4, 45, 6, 10, 8 ]; nechť součet = 22; nech arr_size = A.length; najdi3cisla(A, velikost_arru, soucet); // Tento kód přispěl 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]>součet $r--; } } // Pokud se dostaneme sem, pak // nebyla nalezena žádná trojice return false; } // Kód ovladače $A = pole (1, 4, 45, 6, 10, 8); $součet = 22; $arr_size = sizeof($A); find3Numbers($A, $velikost_arru, $součet); // Tento kód přispěl ajit ?>>>>VýstupTriplet is 4, 8, 10>Analýza složitosti:
- Časová složitost: O(N^2), polem procházejí pouze dvě vnořené smyčky, takže časová složitost je O(n^2). Algoritmus dvou ukazatelů trvá O(n) čas a první prvek lze opravit pomocí dalšího vnořeného procházení.
- Pomocný prostor: O(1), protože není potřeba žádné místo navíc.
Trojitý součet v poli (3 součet) použitím Hašování :
Tento přístup využívá prostor navíc, ale je jednodušší než přístup dvou ukazatelů. Proveďte dvě smyčky vnější smyčku od začátku do konce a vnitřní smyčku od i+1 do konce. Vytvořte hashmap nebo sadu pro uložení prvků mezi nimi i+1 na n-1 . Pokud je tedy daný součet X, zkontrolujte, zda je v sadě číslo, které se rovná X – arr[i] – arr[j] . Pokud ano, vytiskněte trojici.
Postup krok za krokem:
- Iterujte pole a opravte první prvek ( A[i] ) pro trojčata.
- Pro každého A[i] , použijte hashmap pro uložení potenciálních druhých prvků, které dokončí požadovaný součet (součet – A[i]) .
- Uvnitř vnořené smyčky zkontrolujte, zda je rozdíl mezi aktuálním prvkem ( Aj] ) a požadovaný součet ( součet – A[i] ) je přítomen v Hashmap. Pokud ano, je nalezena trojice, pak ji vytiskněte.
- Pokud není v celém poli nalezena žádná trojice, funkce vrátí Nepravdivé .
Níže je uvedena implementace výše uvedeného přístupu:
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_sets; // Vypočítejte aktuální sumu potřebnou k dosažení // cílové sumy int curr_sum = suma - A[i]; // Iterujte podpolí A[i+1..n-1] a najděte // pár s požadovaným součtem pro (int j = i + 1; j // Vypočítejte požadovanou hodnotu pro druhý // prvek int požadovaná_hodnota = curr_sum - A[j] // Zkontrolujte, zda je v sadě // přítomna požadovaná hodnota if (s.find(požadovaná_hodnota) != s.end()) { // Je nalezena trojice /; / elements printf('Triplet je %d, %d, %d', A[i], A[j], požadovaná_hodnota return true } // Přidá aktuální prvek do množiny pro budoucí // doplněk; checks s.insert(A[j] } } // Pokud není nalezen žádný triplet, vrátí false return false } /* Ovladač pro testování výše uvedené funkce */ int main() { int A[] = { 1, 4, 45, 6, 10, 8 }; int sum = 22; int arr_size = sizeof(A) / sizeof(A[0] // Volání funkce find3Numbers pro nalezení a vytištění // tripletu, pokud existuje najdi3čísla(A, velikost_pole, součet návrat 0; >
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 HashSets = nový HashSet (); // Vypočítejte aktuální součet potřebný k dosažení // cílového součtu int curr_sum = sum - arr[i]; // Iterace přes podpole arr[i+1:] for (int j = i + 1; j // Vypočítejte požadovanou hodnotu pro // druhý prvek int required_value = curr_sum - arr[j]; // Zkontrolujte, zda požadovaná hodnota je přítomna v // HashSet if (s.Contains(required_value)) { // Triplet je nalezen vytiskne trojici // prvky Console.WriteLine('Triplet je ' + arr[i] + ', ' + arr[j] + ', ' + požadovaná_hodnota return true } // Přidání aktuálního prvku do HashSet // pro budoucí kontroly doplňku s.Add(arr[j]); Pokud není nalezen žádný triplet, vrátí false return false } // Ovladač otestuje funkci Find3Numbers static void Main() { int[] arr = { 1, 4, 45, 6, 10, 8 }; ; // Volání funkce Find3Numbers pro nalezení a vytištění // tripletu, pokud existuje if (!Find3Numbers(arr, target_sum)) { Console.WriteLine('Nenalezen žádný triplet.'>). řetězec n java>
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();>>>VýstupTriplet is 4, 8, 10>Časová složitost: O(N^2)
Pomocný prostor: O(N), protože bylo zabráno n místa navícVysvětlení problému můžete sledovat na Youtube diskutováno týmem Geeks For Geeks.
Můžete také odkazovat tento video prezentované na Youtube.
Jak vytisknout všechny trojice s daným součtem?
Odkazovat Najděte všechny trojice s nulovým součtem .