-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path3sumCloset.cs
68 lines (57 loc) · 1.5 KB
/
3sumCloset.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _3SumClosest
{
class Program
{
static void Main(string[] args)
{
}
/*
* August 14, 2015
* Leetcode: three sum closest
*/
/*
* http://www.programcreek.com/2013/02/leetcode-3sum-closest-java/
*/
public int threeSumClosest(int[] nums, int target)
{
int min = Int32.MaxValue;
int result = 0;
//Arrays.sort(nums);
nums = sortArray(nums); // work on it later.
for (int i = 0; i < nums.Length; i++)
{
int j = i + 1;
int k = nums.Length - 1;
while (j < k)
{
int sum = nums[i] + nums[j] + nums[k];
int diff = Math.Abs(sum - target);
if (diff == 0) return sum;
if (diff < min)
{
min = diff;
result = sum;
}
if (sum <= target)
{
j++;
}
else
{
k--;
}
}
}
return result;
}
protected int[] sortArray(int[] num)
{
return num;
}
}
}