-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3Sum Closest.cs
More file actions
30 lines (27 loc) · 917 Bytes
/
3Sum Closest.cs
File metadata and controls
30 lines (27 loc) · 917 Bytes
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
public class Solution {
public int ThreeSumClosest(int[] nums, int target) {
Array.Sort(nums);
var closet = int.MaxValue;
for (var i = 0; i < nums.Length - 2; i++) {
if (i != 0 && nums[i] == nums[i - 1]) {
continue;
}
var j = i + 1;
var k = nums.Length - 1;
while (j < k) {
var sum = nums[i] + nums[j] + nums[k];
if (sum == target) {
return target;
} else if (sum < target) {
j++;
} else {
k--;
}
if (closet == int.MaxValue || Math.Abs(sum - target) < Math.Abs(closet - target)) {
closet = sum;
}
}
}
return closet;
}
}