Skip to content

Commit 2e0fdcf

Browse files
Three Sum Closest #109
1 parent 63409ba commit 2e0fdcf

3 files changed

Lines changed: 70 additions & 2 deletions

File tree

Algorithms/LeetCode.Algorithms.Tests/LeetCode.Algorithms.Tests.csproj

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,13 @@
44
<TargetFramework>net6.0</TargetFramework>
55
<ImplicitUsings>enable</ImplicitUsings>
66
<Nullable>enable</Nullable>
7-
7+
<IsTestProject>true</IsTestProject>
88
<IsPackable>false</IsPackable>
99
</PropertyGroup>
1010

1111
<ItemGroup>
1212
<PackageReference Include="FluentAssertions" Version="6.7.0" />
13-
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.1.0" />
13+
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" />
1414
<PackageReference Include="xunit" Version="2.4.2" />
1515
<PackageReference Include="xunit.extensibility.execution" Version="2.4.2" />
1616
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Text.Json;
6+
using System.Threading.Tasks;
7+
8+
namespace LeetCode.Algorithms.Tests;
9+
10+
public class ThreeSumClosestClass
11+
{
12+
[Theory]
13+
[InlineData("[-1,2,1,-4]", 1,2)]
14+
[InlineData("[0,0,0]", 1,0)]
15+
public void ThreeSumClosest(string numsArrayJson, int target ,int expected)
16+
{
17+
var arr = JsonSerializer.Deserialize<int[]>(numsArrayJson);
18+
new Algorithms.ThreeSumClosestClass().ThreeSumClosest(arr, target).Should().Be(expected);
19+
}
20+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Threading.Tasks;
6+
7+
namespace LeetCode.Algorithms;
8+
9+
public class ThreeSumClosestClass
10+
{
11+
public int ThreeSumClosest(int[] nums, int target)
12+
{
13+
if (nums.Length < 3)
14+
return 0;
15+
16+
Array.Sort(nums);
17+
int start = 0;
18+
int left = 1;
19+
int right = nums.Length - 1;
20+
int minDistance = int.MaxValue;
21+
int sum = int.MinValue;
22+
23+
while (start < nums.Length - 2)
24+
{
25+
while (left < right)
26+
{
27+
int currSum = nums[start] + nums[left] + nums[right];
28+
if (currSum == target)
29+
return target;
30+
31+
if (currSum < target)
32+
left++;
33+
else
34+
right--;
35+
36+
if (Math.Abs(currSum - target) < minDistance)
37+
{
38+
sum = currSum;
39+
minDistance = Math.Abs(currSum - target);
40+
}
41+
}
42+
start++;
43+
left = start + 1;
44+
right = nums.Length - 1;
45+
}
46+
return sum;
47+
}
48+
}

0 commit comments

Comments
 (0)