3Sum Closest--LeetCode

来源:互联网 发布:linux安装windows软件 编辑:程序博客网 时间:2024/05/16 19:12

1.题目

3Sum Closest

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).

2.题意

求最接近target的三数之和
假定每个输入都只有一个解决方案

3.分析

要保证三数和跟target差的绝对值最小
brute force时间复杂度为O(n^3)
优化的解法是先排序再左右夹逼
我们需要定义一个变量diff用来记录差的绝对值
先确定一个数,再滑动寻找另外两个数
每确定两个数,求出此三数之和
再算和target的差的绝对值存在newDiff中
然后和diff比较并更新diff和结果result即可
总的时间复杂度为O(n^2+nlogn)=(n^2),空间复杂度是O(1)
一定要特别注意不要遗漏sort(nums.begin(), nums.end());

4.代码

class Solution {public:    int threeSumClosest(vector<int>& nums, int target) {        int result = nums[0] + nums[1] + nums[2];        int diff = abs(result - target);        sort(nums.begin(), nums.end());        for(int i = 0; i < nums.size() - 2; ++i)        {            int j = i + 1;            int k = nums.size() - 1;            while(j < k)            {                int sum = nums[i] + nums[j] + nums[k];                int newDiff = abs(sum - target);                if(newDiff < diff)                {                    result = sum;                    diff = newDiff;                }                if(sum < target)                    ++j;                else                    --k;            }        }        return result;    }};
原创粉丝点击