File tree Expand file tree Collapse file tree 3 files changed +85
-0
lines changed
solution/0000-0099/0016.3Sum Closest Expand file tree Collapse file tree 3 files changed +85
-0
lines changed Original file line number Diff line number Diff line change @@ -242,6 +242,36 @@ var threeSumClosest = function (nums, target) {
242242};
243243```
244244
245+ #### C#
246+
247+ ``` cs
248+ public class Solution {
249+ public int ThreeSumClosest (int [] nums , int target ) {
250+ Array .Sort (nums );
251+ int ans = 1 << 30 ;
252+ int n = nums .Length ;
253+ for (int i = 0 ; i < n ; ++ i ) {
254+ int j = i + 1 , k = n - 1 ;
255+ while (j < k ) {
256+ int t = nums [i ] + nums [j ] + nums [k ];
257+ if (t == target ) {
258+ return t ;
259+ }
260+ if (Math .Abs (t - target ) < Math .Abs (ans - target )) {
261+ ans = t ;
262+ }
263+ if (t > target ) {
264+ -- k ;
265+ } else {
266+ ++ j ;
267+ }
268+ }
269+ }
270+ return ans ;
271+ }
272+ }
273+ ```
274+
245275#### PHP
246276
247277``` php
Original file line number Diff line number Diff line change @@ -241,6 +241,36 @@ var threeSumClosest = function (nums, target) {
241241};
242242```
243243
244+ #### C#
245+
246+ ``` cs
247+ public class Solution {
248+ public int ThreeSumClosest (int [] nums , int target ) {
249+ Array .Sort (nums );
250+ int ans = 1 << 30 ;
251+ int n = nums .Length ;
252+ for (int i = 0 ; i < n ; ++ i ) {
253+ int j = i + 1 , k = n - 1 ;
254+ while (j < k ) {
255+ int t = nums [i ] + nums [j ] + nums [k ];
256+ if (t == target ) {
257+ return t ;
258+ }
259+ if (Math .Abs (t - target ) < Math .Abs (ans - target )) {
260+ ans = t ;
261+ }
262+ if (t > target ) {
263+ -- k ;
264+ } else {
265+ ++ j ;
266+ }
267+ }
268+ }
269+ return ans ;
270+ }
271+ }
272+ ```
273+
244274#### PHP
245275
246276``` php
Original file line number Diff line number Diff line change 1+ public class Solution {
2+ public int ThreeSumClosest ( int [ ] nums , int target ) {
3+ Array . Sort ( nums ) ;
4+ int ans = 1 << 30 ;
5+ int n = nums . Length ;
6+ for ( int i = 0 ; i < n ; ++ i ) {
7+ int j = i + 1 , k = n - 1 ;
8+ while ( j < k ) {
9+ int t = nums [ i ] + nums [ j ] + nums [ k ] ;
10+ if ( t == target ) {
11+ return t ;
12+ }
13+ if ( Math . Abs ( t - target ) < Math . Abs ( ans - target ) ) {
14+ ans = t ;
15+ }
16+ if ( t > target ) {
17+ -- k ;
18+ } else {
19+ ++ j ;
20+ }
21+ }
22+ }
23+ return ans ;
24+ }
25+ }
You can’t perform that action at this time.
0 commit comments