Suma trójek w tablicy (3sumy)
Biorąc pod uwagę tablicę arr[] wielkościowy N i liczbę całkowitą X . Sprawdź, czy w tablicy znajduje się trójka, której suma wynosi podaną liczbę całkowitą X .
Przykłady:
Zalecana praktyka Suma trójek w tablicy Wypróbuj!Wejście: tablica = {12, 3, 4, 1, 6, 9}, suma = 24;
Wyjście: 12, 3, 9
Wyjaśnienie: Obecna jest trójka (12, 3 i 9).
w tablicy, której suma wynosi 24.Wejście: tablica = {1, 2, 3, 4, 5}, suma = 9
Wyjście: 5, 3, 1
Wyjaśnienie: Istnieje trójka (5, 3 i 1).
w tablicy, której suma wynosi 9.
Suma trójek w tablicy (3sumy) generując wszystkie trójki:
Prostą metodą jest wygenerowanie wszystkich możliwych trójek i porównanie sumy każdej trójki z podaną wartością. Poniższy kod implementuje tę prostą metodę przy użyciu trzech zagnieżdżonych pętli.
Podejście krok po kroku:
- Biorąc pod uwagę tablicę długości N i suma S
- Utwórz trzy zagnieżdżone pętle. Pierwsza pętla przebiega od początku do końca (licznik pętli i), a druga pętla przebiega od ja+1 do końca (licznik pętli j) i od niego biegnie trzecia pętla j+1 do końca (licznik pętli k)
- Licznik tych pętli reprezentuje indeks 3 elementy trojaczków.
- Znajdź sumę i-tego, j-tego i k-tego elementu. Jeśli suma jest równa podanej sumie. Wydrukuj trójkę i podziel.
- Jeśli nie ma trójki, wypisz, że trójki nie ma.
Poniżej implementacja powyższego podejścia:
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; }> |
Jawa
// 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 ?>> |
Wyjście
Triplet is 4, 10, 8
Analiza złożoności:
- Złożoność czasowa: NA 3 ), Istnieją trzy zagnieżdżone pętle przechodzące przez tablicę, więc złożoność czasowa wynosi O(n^3)
- Przestrzeń pomocnicza: O(1), Ponieważ nie jest wymagana dodatkowa przestrzeń.
Suma trójek w tablicy (3sumy) za pomocą Technika dwóch wskaźników :
Sortując tablicę, można poprawić wydajność algorytmu. To efektywne podejście wykorzystuje technika dwóch punktów . Przejdź przez tablicę i napraw pierwszy element trójki. Teraz użyj algorytmu dwóch wskaźników, aby sprawdzić, czy istnieje para, której suma jest równa x – tablica[i] . Algorytm dwóch wskaźników zajmuje czas liniowy, więc jest lepszy niż pętla zagnieżdżona.
Podejście krok po kroku:
- Posortuj podaną tablicę.
- Wykonaj pętlę nad tablicą i napraw pierwszy element możliwej trójki, Arr[i] .
- Następnie napraw dwa wskaźniki, jeden w ja + 1 a drugi o godz n – 1 . I spójrz na sumę,
- Jeśli suma jest mniejsza od wymaganej, zwiększ pierwszy wskaźnik.
- W przeciwnym razie, jeśli suma jest większa, zmniejsz wskaźnik końcowy, aby zmniejszyć sumę.
- W przeciwnym razie, jeśli suma elementów w punkcie dwuwskaźnikowym jest równa podanej sumie, wypisz trójkę i podziel.
Poniżej implementacja powyższego podejścia:
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]>suma r--; } } // Jeśli dotrzemy tutaj, oznacza to, że nie znaleziono trójki return false; } /* Program sterownika do testowania powyższej funkcji */ int main() { int A[] = { 1, 4, 45, 6, 10, 8 }; suma całkowita = 22; int arr_size = rozmiar(A) / rozmiar(A[0]); find3Numbers(A, rozmiar_tablicy, suma); zwróć 0; } // Autorem tego kodu jest 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]>suma r--; } } // Jeśli dotrzemy tutaj, oznacza to, że nie znaleziono trójki return false; } /* Program sterownika do testowania powyższej funkcji */ int main() { int A[] = { 1, 4, 45, 6, 10, 8 }; suma całkowita = 22; int arr_size = rozmiar(A) / rozmiar(A[0]); find3Numbers(A, rozmiar_tablicy, suma); zwróć 0; } // Autorem tego kodu jest Aditya Kumar (adityakumar129)> |
Jawa
// 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]>suma r--; } } // Jeśli dotrzemy tutaj, oznacza to, że nie znaleziono trójki return false; } int partycja(int A[], int si, int ei) { int x = A[ei]; int i = (si - 1); int j; dla (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[] -->Tablica do sortowania si --> Indeks początkowy ei --> Indeks końcowy */ void QuickSort(int A[], int si, int ei) { int pi; /* Indeks partycjonowania */ if (si pi = partycja(A, si, ei); QuickSort(A, si, pi - 1); QuickSort(A, pi + 1, ei); } } // Program sterownika do testowania powyższe funkcje public static void main(String[] args) { FindTriplet triplet = new FindTriplet(); int A[] = { 1, 4, 45, 6, 10, 8 }; int sum = 22; długość; triplet.find3Numbers(A, rozmiar_tablicy, suma); |
>
# 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]suma r -= 1 # Jeśli dotrzemy tutaj, to # nie znaleziono trójki. return False # Program sterownika testujący powyższą funkcję A = [1, 4, 45, 6, 10, 8] sum = 22 arr_size = len(A) find3Numbers(A, arr_size, sum) # Autorem jest 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]>suma r--; } } // Jeśli dotrzemy tutaj, // nie znaleziono trójki return false; } int partycja(int[] A, int si, int ei) { int x = A[ei]; int i = (si - 1); int j; dla (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[] -->Tablica do sortowania si --> Indeks początkowy ei --> Indeks końcowy */ void QuickSort(int[] A, int si, int ei) { int pi; /* Indeks partycjonowania */ if (si pi = partycja(A, si, ei); QuickSort(A, si, pi - 1); QuickSort(A, pi + 1, ei); } } // Kod sterownika static void Main() { Triplet GFG = nowy GFG(); int[] A = nowy int[] { 1, 4, 45, 6, 10, 8 }; int suma = 22; int arr_size = A.Length; (A, arr_size, sum); } } // Ten kod został napisany przez 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]>suma r--; } } // Jeśli dotrzemy tutaj, oznacza to, że nie znaleziono trójki return false; } /* Program sterownika testujący powyższą funkcję */ let A = [ 1, 4, 45, 6, 10, 8 ]; niech suma = 22; niech arr_size = A.length; find3Numbers(A, rozmiar_tablicy, suma); // Ten kod został napisany przez Mayanka 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]>suma $r--; } } // Jeśli dotrzemy tutaj, // nie znaleziono trójki return false; } // Kod sterownika $A = tablica (1, 4, 45, 6, 10, 8); $suma = 22; $arr_size = rozmiar($A); find3Numbers($A, $arr_size, $suma); // Ten kod został stworzony przez ajit ?>>
Wyjście
Triplet is 4, 8, 10Analiza złożoności:
- Złożoność czasowa: O(N^2). W tablicy przechodzą tylko dwie zagnieżdżone pętle, więc złożoność czasowa wynosi O(n^2). Algorytm dwóch wskaźników zajmuje czas O(n), a pierwszy element można ustalić za pomocą innego zagnieżdżonego przejścia.
- Przestrzeń pomocnicza: O(1), Ponieważ nie jest wymagana dodatkowa przestrzeń.
Suma trójek w tablicy (3sumy) za pomocą Haszowanie :
To podejście wymaga dodatkowej przestrzeni, ale jest prostsze niż podejście dwuwskaźnikowe. Uruchom dwie pętle: zewnętrzną pętlę od początku do końca i wewnętrzną pętlę od ja+1 do końca. Utwórz mapę mieszającą lub ustaw przechowywanie elementów pomiędzy nimi ja+1 Do n-1 . Jeśli więc podana suma wynosi X, sprawdź, czy w zbiorze znajduje się liczba równa X – arr[i] – arr[j] . Jeśli tak, wydrukuj trójkę.
Podejście krok po kroku:
- Iteruj po tablicy, naprawiając pierwszy element ( A[i] ) dla trójki.
- Dla każdego A[i] , użyj Hashmapy do przechowywania potencjalnych drugich elementów, które uzupełniają żądaną sumę (suma – A[i]) .
- Wewnątrz zagnieżdżonej pętli sprawdź, czy różnica między bieżącym elementem ( A[j] ) i żądaną sumę ( suma – A[i] ) jest obecny w Hashmapie. Jeśli tak, zostanie znaleziona trójka, a następnie wydrukuj ją.
- Jeżeli w całej tablicy nie zostanie znaleziona trójka, funkcja zwraca FAŁSZ .
Poniżej implementacja powyższego podejścia:
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; // Oblicz aktualną sumę potrzebną do osiągnięcia // sumy docelowej int curr_sum = sum - A[i]; // Wykonaj iterację po podtablicy A[i+1..n-1], aby znaleźć // parę z wymaganą sumą dla (int j = i + 1; j // Oblicz wymaganą wartość dla drugiego // elementu int wymagana_wartość = curr_sum - A[j]; // Sprawdź, czy wymagana wartość znajduje się w // zestawie if (s.find(required_value) != s.end()) { // Znaleziono trójkę, wydrukuj trójkę; / elementy printf('Trójka to %d, %d, %d', A[i], A[j], wymagana_wartość); return true; } // Dodaj bieżący element do zbioru w celu przyszłego // uzupełnienia sprawdza s.insert(A[j]); } } // Jeśli nie zostanie znaleziona trójka, zwróć fałsz return false; } /* Program sterownika testujący powyższą funkcję */ int main() { int A[] = { 1, 4, 45, 6, 10, 8 }; int sum = 22; int arr_size = sizeof(A) / sizeof(A[0]); // Wywołaj funkcję find3Numbers, aby znaleźć i wydrukować trójkę, // jeśli istnieje find3Numbers(A, rozmiar_tablicy, suma); return 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 = nowy zestaw HashSet (); // Oblicz aktualną sumę potrzebną do osiągnięcia // sumy docelowej int curr_sum = sum - arr[i]; // Wykonaj iterację po podtablicy arr[i+1:] for (int j = i + 1; j // Oblicz wymaganą wartość dla // drugiego elementu int require_value = curr_sum - arr[j]; // Sprawdź, czy wymagana wartość jest obecna w // HashSet if (s.Contains(required_value)) { // Znaleziono trójkę; wydrukuj trójkę // elementy Console.WriteLine('Trójka to ' + arr[i] + ', ' + arr[j] + ', ' + wymagana_wartość return true; } // Dodaj bieżący element do zestawu HashSet // w celu sprawdzenia uzupełnienia w przyszłości s.Add(arr[j]); Jeśli nie zostanie znaleziona trójka, zwróć fałsz return false; } // Program sterownika testujący funkcję Find3Numbers static void Main() { int[] arr = { 1, 4, 45, 6, 10, 8 }; ; // Wywołaj funkcję Find3Numbers, aby znaleźć i wydrukować // trójkę, jeśli istnieje if (!Find3Numbers(arr, target_sum)) { Console.WriteLine('Nie znaleziono trójki.' } } }>'>);
>
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();>
Wyjście
Triplet is 4, 8, 10Złożoność czasowa: O(N^2)
Przestrzeń pomocnicza: O(N), ponieważ zajęto n dodatkowej przestrzeniWyjaśnienie problemu można obejrzeć na stronie Youtube omówione przez zespół Geeks For Geeks.
Możesz także polecić Ten wideo obecne na Youtube.
Jak wydrukować wszystkie trójki z podaną sumą?
Wspominać Znajdź wszystkie trójki z sumą zerową .