Swift
52ms
class Solution {
func threeSumClosest(_ nums: [Int], _ target: Int) -> Int {
let copyNums = nums.sorted{$0 < $1}
if copyNums.count < 3 {
return 0
}
var res = 0; var dist = Int32.max
for i in 0..<copyNums.count - 2 {
if (i > 0 && copyNums[i] == copyNums[i - 1] ) {
continue
}
var j = i + 1
var k = nums.count - 1
var sum = 0
while j < k {
sum = copyNums[i] + copyNums[j] + copyNums[k]
if sum == target {
return sum
}
if (abs(sum - target) < dist) {
dist = Int32(abs(sum - target))
res = sum
}
if sum < target {
j += 1
} else {
k -= 1
}
}
}
return res
}
}
C++
12ms
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
if (nums.size() < 3) return 0;
sort(nums.begin(), nums.end());
int closet = nums[0] + nums[1] + nums[2];
for(int first = 0; first < nums.size() -2; first++)
{
if(first > 0 && nums[first] == nums[first -1]) continue;
int second = first + 1;
int third = nums.size() -1;
while (second < third) {
int curSum = nums[first] +nums[second] + nums[third];
if (curSum == target) return curSum;
if (abs(target - curSum) < abs(target - closet)) {
closet = curSum;
}
if (curSum < target) {
++second;
} else {
--third;
}
}
}
return closet;
}
};
网友评论