
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to find the unique triplet that is close to the given target using C#?
Two Pointers pattern and is similar to Triplet Sum to Zero. We can follow a similar approach to iterate through the array, taking one number at a time. At every step, we will save the difference between the triplet and the target number, and at each step we will compare it with the minimum target difference so far, so that in the end, we can return the triplet with the closest sum.
Time complexity
Sorting the array will take O(N* logN). Overall threeSumClosest() will take O(N * logN + N^2), which is asymptotically equivalent to O(N^2).
Space complexity
The space complexity of the above algorithm will be O(N) which is required for sorting.
Example
public class Arrays{ public int ThreeSumClosest(int[] num, int target){ if (num == null || num.Length == 0){ return -1; } int[] nums = num.OrderBy(x => x).ToArray(); int initialclosest = nums[0] + nums[1] + nums[2]; for (int i = 0; i < nums.Count(); i++){ int left = i + 1; int right = nums.Length - 1; while (left < right){ int newClosest = nums[i] + nums[left] + nums[right]; if (Math.Abs(newClosest - target) < Math.Abs(initialclosest - target)){ initialclosest = newClosest; } if (newClosest == target){ return newClosest; } else if (newClosest < target){ left++; } else { right--; } } } return initialclosest; } } static void Main(string[] args){ Arrays s = new Arrays(); int[] nums = { -1, 2, 1, -4 }; Console.WriteLine(s.ThreeSumClosest(nums, 1)); }
Output
2
- Related Questions & Answers
- How to find the quadruplet that is close to target using C#?
- How to find all the unique quadruplets that is close to zero using C#?
- How to find the target sum from the given array by backtracking using C#?
- Find a triplet that sum to a given value in C++
- How to find the unique combination k sum that corresponds to k sum using C#?
- How to find the unique combination of sum from the given number C#?
- How to find all unique triplets that adds up to sum Zero using C#?
- Find the index of the first unique character in a given string using C++
- Find probability that a player wins when probabilities of hitting the target are given in C++
- Program to find number of unique subsequences same as target in C++
- Program to find minimum distance to the target element using Python
- How to close all the opened files using Python?
- Find if there is a triplet in a Balanced BST that adds to zero in C++
- Find the Number of Unique Triplets Whose XOR is Zero using C++
- Find triplet such that number of nodes connecting these triplets is maximum in C++
Advertisements