# Leetcode 16. 3Sum Closest

## 2. Solution

• Brute Force
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int length = nums.size();
int sum = nums[0] + nums[1] + nums[2];
int min = abs(sum - target);
for(int i = 0; i < length; i++) {
for(int j = i + 1; j < length; j++) {
for(int k = j + 1; k < length; k++) {
int temp = nums[i] + nums[j] + nums[k];
int diff = abs(temp - target);
if(min > diff) {
min = diff;
sum = temp;
}
}
}
}
return sum;
}
};
• sort and O(n^2)
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
// sort vector
sort(nums.begin(), nums.end());
int length = nums.size();
int sum = nums[0] + nums[1] + nums[2];
int min = abs(sum - target);
for(int i = 0; i < length - 2; i++) {
int left = i + 1;
int right = length - 1;
while(left < right) {
int temp = nums[i] + nums[left] + nums[right];
int diff = abs(temp - target);
if(min > diff) {
min = diff;
sum = temp;
}
if(temp < target) {
left++;
}
else if(temp > target) {
right--;
}
else {
return temp;
}
}
}
return sum;
}
};

SnailTyan

• 擅长领域：
• 深度学习
• PyTorch
• OCR
• Docker
• Caffe