Skip to content

Instantly share code, notes, and snippets.

@kinshuk4
Created July 10, 2016 07:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kinshuk4/eed182627f6c7cf5a7e94282801569a6 to your computer and use it in GitHub Desktop.
Save kinshuk4/eed182627f6c7cf5a7e94282801569a6 to your computer and use it in GitHub Desktop.
class Solution{
boolean threeSumBruteForce(int arr[], int sum)
{
int n = arr.length;
// Fix the first element as A[i]
for (int i = 0; i < n-2; i++)
{
// Fix the second element as A[j]
for (int j = i+1; j < n-1; j++)
{
// Now look for the third number
for (int k = j+1; k < n; k++)
{
if (arr[i] + arr[j] + arr[k] == sum)
{
System.out.printf("Triplet is %d, %d, %d", arr[i], arr[j], arr[k]);
return true;
}
}
}
}
// If we reach here, then no triplet was found
return false;
}
boolean threeSumSorting(int A[], int sum)
{
int l, r;
int n = A.length;
Arrays.sort(A);
// Now fix the first element one by one and find the
// other two elements
for (int i = 0; i < n - 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 = n-1; // index of the last element
while (l < r)
{
if( A[i] + A[l] + A[r] == sum)
{
System.out.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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment