Created
May 18, 2016 00:59
-
-
Save jianminchen/d23598296e7ba665b6d45ae4acfeb600 to your computer and use it in GitHub Desktop.
Leetcode 16 - 3 sum closest - C# warm up practice
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace _15_3sumClosest | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// test 3 sum closest | |
int[] arr = new int[4] { -1, 2, 1, -4}; | |
Console.WriteLine(threeSumClosest(arr, 1)); | |
} | |
/* | |
* May 17, 2016 | |
* Work on this 3 sum closest algorithm | |
* Idea: | |
* 1. Sorting takes O(nlogn) for an array | |
* 2. And then, choose (i, j, k), assuming i<j<k, iterate on variable i, | |
* we need to find two sum problem for each i, new target = target - nums[i] | |
* since the array is sorted, two pointer solution can be used. One is the beginning | |
* of array, another one is the end of the array. | |
* | |
* So, this step 2 process takes O(n^2) time | |
* | |
* Overall, the algorithm will take O(n^2) time complexity | |
* | |
* | |
* read the C# Array API - 10 minutes | |
* https://msdn.microsoft.com/en-us/library/6tf1f0bc(v=vs.110).aspx | |
* | |
* Julia enjoyed the writng of the code. | |
* 1. First, write the code. | |
* 2. Second, review the code, every line, every variable, every executable path, | |
* no bug please. | |
*/ | |
public static int threeSumClosest(int[] nums, int target) | |
{ | |
int minValue = Int32.MaxValue; | |
int closestValue = 0; | |
Array.Sort(nums); | |
for (int i = 0; i < nums.Length; i++) | |
{ | |
// range is [i+1, nums.Length -1] | |
int start = i + 1; | |
int end = nums.Length - 1; | |
int firstValue = nums[i]; | |
while (start < end) // two pointers technique - sliding to the center. | |
{ | |
int newSum = firstValue + nums[start] + nums[end]; | |
int newGap = Math.Abs(newSum - target); | |
if (newSum == target) | |
return target; | |
if (newGap < minValue) | |
{ | |
minValue = newGap; | |
closestValue = newSum ; | |
} | |
if (newSum < target) | |
{ | |
start++; | |
} | |
else | |
{ | |
end--; | |
} | |
} | |
} | |
return closestValue; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment