zoukankan      html  css  js  c++  java
  • [LeetCode] #16 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).

     本文是3sum问题的变更,是寻找到最接近目标值的三数组合,利用diff存放与目标最小的差距,如果diff=0,即可输出。

    参考的3sum问题http://www.cnblogs.com/Scorpio989/p/4440236.html

    时间:15ms。代码如下:

    class Solution {
    public:
        int threeSumClosest(vector<int>& nums, int target) {
            int besttarget = 0, diff = INT_MAX;
            sort(nums.begin(), nums.end());
            for (int i = 0; i < nums.size() - 2; i++){
                int j = i + 1, n = nums.size() - 1;
                if (i>0 && nums[i] == nums[i - 1])
                    continue;
                while (j < n){
                    if (j>i + 1 && nums[j] == nums[j - 1]){
                        j++;
                        continue;
                    }
                    if (n<nums.size() - 1 && nums[n] == nums[n + 1]){
                        n--;
                        continue;
                    }
                    int sum = nums[i] + nums[j] + nums[n];
                    if (abs(sum - target) < diff){
                        diff = abs(sum - target);
                        besttarget = sum;
                    }
                    if (sum == target)
                        return besttarget;
                    else if (sum>target)
                        n--;
                    else
                        j++;
                }
            }
            return besttarget;
        }
    };
    “If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
  • 相关阅读:
    Java-笔记9-复习
    Java-笔记9
    Java-笔记8-复习
    Java0-笔记8
    Java-笔记7-复习
    hadoop-hdfs-ha配置-搭建
    Java-笔记7
    Java-笔记6-复习
    kettle-作业和参数
    kettle-脚本控件
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4444353.html
Copyright © 2011-2022 走看看