zoukankan      html  css  js  c++  java
  • leetcode133:3sum-closest

    题目描述

    给出含有n个整数的数组s,找出s中和加起来的和最接近给定的目标值的三个整数。返回这三个整数的和。你可以假设每个输入都只有唯一解。
       例如,给定的整数 S = {-1 2 1 -4}, 目标值 = 1.↵↵   最接近目标值的和为 2. (-1 + 2 + 1 = 2).
     

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

    示例1

    输入

    复制
    [0,0,0],1

    输出

    复制
    0
    链接:https://www.nowcoder.com/questionTerminal/291a866d7c904563876b373b0b157dde?f=discussion
    来源:牛客网

    class Solution {
    public:
        int threeSumClosest(vector<int> &num, int target) {
            int n = num.size();
            int result = num[0] + num[1] + num[n-1];
            sort(num.begin(),num.end());
            for(int i=0;i<n-2;i++)
            {
                int start = i + 1;
                int end = n - 1;
                while(start < end)
                {
                    int sum = num[i] + num[start] + num[end];
                    if(sum < target)
                        start++;
                    else
                        end--;
                     
                    if(abs(sum-target) < abs(result-target))
                        result = sum;
                }
            }
            return result;
        }
    };



  • 相关阅读:
    IBM Minus One(water)
    约瑟夫问题的循环链表实现
    双向链表(差不多)
    单向链表的建立,插入,删除(复习一下)
    找新朋友(欧拉函数)
    验证角谷猜想(hd1279)
    Wolf and Rabbit(gcd)
    Big Number(大数)
    字串数(高精度组合数)
    寻找素数对(hd1262)
  • 原文地址:https://www.cnblogs.com/hrnn/p/13417114.html
Copyright © 2011-2022 走看看