LeetCode_16. 3Sum Closest

一、题目描述

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

大致意思:

求数组中三个元素的和与给定的目标数值最接近,并且最后返回最接近的三个元素的和。

二、解题思路

1:暴力法

利用三重循环将所有的元素相加然后求误差,用loss记录误差如果当前误差小则更新误差,最后返回target-loss

(当将loss初始化为INT_MN时,在求绝对值时会出现溢出)

2:

利用排序加指针解决时间复杂度O(N^2)+O(long2N)

对第一个数循环取其下标 I ,对第二个数令其为 I -1 ,第三个数为  nums.size()-1,根据当前和的大小决定是第二个数后移还是第三个数前移动。

三、代码

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        int ans=INT_MIN+1;
        int i,j,k;
        int len=nums.size();
        sort(nums.begin(),nums.end());
        int flag=0;
        for(i=0;i<len-2;i++)
        {
           j=i+1;
        k=len-1;
            while(j<k)
            {
                int sum=nums[i]+nums[j]+nums[k];
                //利用ans 存放当前误差最小的3数之和,若果当前比sum大则k--,如果当前比sum 小则j++;
                if(flag==0)//如果是第一次循环把第一个和暂时赋值给ans
                {
                    ans=sum;
                    flag=1;
                }
                if(abs(target-ans)>abs(target-sum))
                {ans=sum;
                }
                if(sum<target)
                {
                    j++;
                }
                else{
                    k--;
                }
            }
        }
        
        return ans;
        
        
    }
};

  

 
原文地址:https://www.cnblogs.com/zydxx/p/10011144.html