题目:
16. 3Sum Closest
- Total Accepted: 126037
- Total Submissions: 408305
- Difficulty: Medium
- Contributor: LeetCode
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).
Subscribe to see which companies asked this question.
解题思路:题目要求的是数组中三个数之和与target相差最小的和值。我们先将数组升序排序,先固定第一个值,然后从数组两边分别向中间扫描以确定第二和第三个值,然后对其求和,赋为sum,将第一次求和的值赋为val,然后比较sum和val与target之差的绝对值,若abs(sum - target) < abs(val - target),则将sum赋给val,若val等于target,则直接返回target即可。否则比较sum和target的大小,若sum > target,则第三个数往左扫描,否则第二个数往右扫描。同时在扫描时注意跳过相等的值。
解答:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int n = nums.size() ;
int val = nums[0] + nums[1] + nums[n -1];
sort(nums.begin(),nums.end());
for(int i = 0;i < n; i ++){
while(i > 0 && i < n && nums[i] == nums[i -1]){
i ++;
}
int j = i +1;
int k = n -1;
while(j < k){
int sum = nums[i] + nums[j] +nums[k];
if(abs(sum - target) < abs(val - target)){
val = sum;
}
if(val == target){
return val;
}
if(sum > target){
k --;
while(k > j && nums[k] == nums[k+1]){
k --;
}
}
else{
j ++;
while(j < k && nums[j] == nums[j -1]){
j ++;
}
}
}
}
return val;
}
};