16. 3Sum Closest[M]最接近的三数之和

题目

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


思路

思路:三指针法

对于一个数组S,求数组中三个数a、b、c的和,使之最接近target。将问题抽象化为,求一个min使得:

[min = arg min | target - min | quad s.t. quad min =a+b+c ]

即求出使得$| target - min | $时min的值。
三指针法,见题[15]。三指针方法的关键是:

  • 判断三个指针的移动的方向与条件(首先对数组排序)
    • 如果min < target,说明min太小了,不够接近target,将中间指针往大的方向移动
    • 如果min = target,由于只有一个结果,故可以直接返回
    • 如果min < target,说明min太大了,超出了target,将尾指针往小的方向移动
  • 状态的更新
    • 保证min始终是指针移动过程中a+b+c的最小值。
  • 注意
    • 每次只移动一个指针

C++

int threeSumClosest(vector<int>& nums, int target) {

        sort(nums.begin(),nums.end());       //对数组排序
        int min=nums[0]+nums[1]+nums[2];   //初始化最小值
        
        for(int pBegin=0;pBegin<nums.size();pBegin++){
            
            int pMid = pBegin+1;//中间指针
            int pEnd=nums.size()-1;//尾指针
            
            int sub=target-nums[pBegin];
            
            while(pMid<pEnd){
              
                if(abs(sub-nums[pMid]-nums[pEnd]) < abs(target-min))  //更新最接近target时的和
                    min = nums[pBegin]+nums[pMid]+nums[pEnd];
                
                if(nums[pMid]+nums[pEnd] == sub){
                    return target;
                }
                else if(nums[pMid]+nums[pEnd] > sub){
                    pEnd--;
                }
                else{
                    pMid++;
                }
            }
        }
        return min;
    }

Python

class Solution(object):
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        nums.sort()
        minVal = nums[0]+nums[1]+nums[2]
        
        for pBegin in range (len(nums)):
            pMid = pBegin + 1
            pEnd = len(nums) - 1
            subVal = target - nums[pBegin]
            
            while pMid < pEnd:
                if abs(subVal - nums[pMid] - nums[pEnd]) < abs(target - minVal):
                    minVal = nums[pBegin] + nums[pMid] + nums[pEnd]
                
                if nums[pMid] + nums[pEnd] == subVal:
                    return target
                elif nums[pMid] + nums[pEnd] > subVal:
                    pEnd -= 1
                else:
                    pMid += 1
        return minVal
原文地址:https://www.cnblogs.com/Jessey-Ge/p/10993493.html