-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy path3SumClosest.cs
executable file
·80 lines (77 loc) · 5.05 KB
/
3SumClosest.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Source : https://leetcode.com/problems/3sum-closest/
// Author : codeyu
// Date : Thursday, October 6, 2016 8:22:54 AM
/***************************************************************************************
*
* Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target.
* Return the sum of the three integers.
* You may assume that each input would have exactly one solution.
*
*
* For example, given array S = {-1 2 1 -4}, and target = 1.
*
* The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
*
*
**********************************************************************************/
using System;
using Algorithms.Utils;
namespace Algorithms
{
public class Solution016
{
public static int ThreeSumClosest(int[] nums, int target)
{
var result = 0;
var minDiff = int.MaxValue;
Helper.BubbleSort2(nums);
for(int i = 0; i < nums.Length-2; i++)
{
var j = i + 1;
var k = nums.Length - 1;
while(j < k)
{
var sum = nums[i] + nums[j] + nums[k];
var diff = Math.Abs(sum - target);
if(minDiff > diff)
{
result = sum;
minDiff = diff;
}
else if(sum < target)
{
j++;
}
else if(sum > target)
{
k--;
}
else
{
return result;
}
}
}
return result;
}
public static int ThreeSumClosest2(int[] nums, int target)
{
if(nums.Length < 3) throw new Exception();
Helper.BubbleSort3(nums);
var minDiff = int.MaxValue;
for(int i = 0; i < nums.Length - 2; i++)
{
int left = i+1,right = nums.Length - 1;
while(left < right)
{
int diff = nums[i] + nums[left] + nums[right] - target;
if(Math.Abs(diff) < Math.Abs(minDiff)){ minDiff = diff; }
if(diff == 0) { break; }
else if(diff < 0) { left ++; }
else { right --; }
}
}
return target + minDiff;
}
}
}