From 4eb8c6237ff7169c9c04b09ca8195186b2031806 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Velimir=20=C4=90urkovi=C4=87?= Date: Wed, 5 Feb 2025 21:23:55 +0100 Subject: [PATCH] feat: add csharp solution to lc problem: No.0016 --- .../0000-0099/0016.3Sum Closest/README.md | 30 +++++++++++++++++++ .../0000-0099/0016.3Sum Closest/README_EN.md | 30 +++++++++++++++++++ .../0000-0099/0016.3Sum Closest/Solution.cs | 25 ++++++++++++++++ 3 files changed, 85 insertions(+) create mode 100644 solution/0000-0099/0016.3Sum Closest/Solution.cs 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