diff --git a/solution/0000-0099/0016.3Sum Closest/README.md b/solution/0000-0099/0016.3Sum Closest/README.md index 26a419cdec0e9..406e23f70dbb9 100644 --- a/solution/0000-0099/0016.3Sum Closest/README.md +++ b/solution/0000-0099/0016.3Sum Closest/README.md @@ -242,6 +242,36 @@ var threeSumClosest = function (nums, target) { }; ``` +#### C# + +```cs +public class Solution { + public int ThreeSumClosest(int[] nums, int target) { + Array.Sort(nums); + int ans = 1 << 30; + int n = nums.Length; + for (int i = 0; i < n; ++i) { + int j = i + 1, k = n - 1; + while (j < k) { + int t = nums[i] + nums[j] + nums[k]; + if (t == target) { + return t; + } + if (Math.Abs(t - target) < Math.Abs(ans - target)) { + ans = t; + } + if (t > target) { + --k; + } else { + ++j; + } + } + } + return ans; + } +} +``` + #### PHP ```php diff --git a/solution/0000-0099/0016.3Sum Closest/README_EN.md b/solution/0000-0099/0016.3Sum Closest/README_EN.md index 92375933a0907..b5ccdf0198cd0 100644 --- a/solution/0000-0099/0016.3Sum Closest/README_EN.md +++ b/solution/0000-0099/0016.3Sum Closest/README_EN.md @@ -241,6 +241,36 @@ var threeSumClosest = function (nums, target) { }; ``` +#### C# + +```cs +public class Solution { + public int ThreeSumClosest(int[] nums, int target) { + Array.Sort(nums); + int ans = 1 << 30; + int n = nums.Length; + for (int i = 0; i < n; ++i) { + int j = i + 1, k = n - 1; + while (j < k) { + int t = nums[i] + nums[j] + nums[k]; + if (t == target) { + return t; + } + if (Math.Abs(t - target) < Math.Abs(ans - target)) { + ans = t; + } + if (t > target) { + --k; + } else { + ++j; + } + } + } + return ans; + } +} +``` + #### PHP ```php diff --git a/solution/0000-0099/0016.3Sum Closest/Solution.cs b/solution/0000-0099/0016.3Sum Closest/Solution.cs new file mode 100644 index 0000000000000..d58947aab214b --- /dev/null +++ b/solution/0000-0099/0016.3Sum Closest/Solution.cs @@ -0,0 +1,25 @@ +public class Solution { + public int ThreeSumClosest(int[] nums, int target) { + Array.Sort(nums); + int ans = 1 << 30; + int n = nums.Length; + for (int i = 0; i < n; ++i) { + int j = i + 1, k = n - 1; + while (j < k) { + int t = nums[i] + nums[j] + nums[k]; + if (t == target) { + return t; + } + if (Math.Abs(t - target) < Math.Abs(ans - target)) { + ans = t; + } + if (t > target) { + --k; + } else { + ++j; + } + } + } + return ans; + } +} \ No newline at end of file