LeetCode 16. 3Sum Closest (Two-Pointer)
2540 ワード
タイトルの説明
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).
テーマ解析
この問題は15題3 Sumと似ている.まずソートを行い、iが1からcnt-2まで遍歴するように構築する.jとkの構造two-pointer法を用いてleetcode 11題を詳しく紹介する
コード#コード#
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).
テーマ解析
この問題は15題3 Sumと似ている.まずソートを行い、iが1からcnt-2まで遍歴するように構築する.jとkの構造two-pointer法を用いてleetcode 11題を詳しく紹介する
コード#コード#
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int cnt = nums.size();
assert(cnt>=3);
sort(nums.begin(),nums.end());
int ans = nums[0]+nums[1]+nums[2];
for(int i = 0;i2;++i)
{
if(i>1&&nums[i]==nums[i-1])
{
continue;
}
int j = i+1,k=cnt-1; //
while(jint sum = nums[i]+nums[j]+nums[k];
if(abs(sum-target)<abs(ans-target))
{
ans = sum;
}
if(sum == target)
{
return target;
}
if(sumelse
{
--k;
}
}
}
return ans;
}
};