[leetcode]16. 3Sum Closest

Description

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

分析

  • 这道题对一开始上手的人来说,可能思维不难,但是代码写好的话,就有点困难,比如在寻找之前先从小到大排序,用diff来记录目标和最近的差值,然后遍历寻找。
  • for(){
    while(left }
    }
    这种模式在leetcode的其他几个题中会遇见,这可以作为这一类题目的通用解法。
  • 解法有点暴力

代码

class Solution {
public:
    int threeSumClosest(vector& nums, int target) {
        sort(nums.begin(),nums.end());
        int closet=nums[0]+nums[1]+nums[2];
        int diff=abs(closet-target);
        for(int i=0;iabs(sum-target)){
                    diff=abs(sum-target);
                    closet=sum;
                }
                if(sum

参考文献

[LeetCode] 3Sum Closest 最近三数之和

你可能感兴趣的:(C++,leetcode,leetcode题解)