每日算法——leetcode系列
問題 3Sum Closest
Difficulty: Medium
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.
<pre>
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).
</pre>
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
}
};
翻譯
三數和
難度系數:中等
給定一個有n個整數的數組S, 找出數組S中三個數的和最接近一個指定的數。 返回這三個數的和。 你可以假定每個輸入都有一個結果。
思路
思路跟3Sum很像, 不同的就是不用去重復, 要記錄三和最接近target的和值。
代碼
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int result = 0;
int minDiff = INT32_MAX;
// 排序
sort(nums.begin(), nums.end());
int n = static_cast<int>(nums.size());
for (int i = 0; i < n - 2; ++i) {
int j = i + 1;
int k = n - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
int diff = abs(sum - target);
// 記錄三和最接近target的和值
if (minDiff > diff){
result = sum;
minDiff = diff;
}
else if (sum < target){
j++;
}
else if (sum > target){
k--;
}
else{
return result;
}
}
}
return result;
}
};