zoukankan      html  css  js  c++  java
  • Leetcode 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差不多
    class Solution {
    public:
        int threeSumClosest(vector<int> &num, int target) {
            sort(num.begin(),num.end());
            int closet = num[0]+num[1]+num[2];
            for(int i = 0 ; i < num.size()-2; ++ i){
                int start = i+1, end = num.size()-1,sum = 0;
                while(start <  end){
                    sum = num[i] + num[start] + num[end];
                    if(sum == target) return sum;
                    else if(sum > target) end--;
                    else start++;
                    closet = abs(sum - target) < abs(closet-target) ? sum : closet;
                }
            }
            return closet;
        }
    };
    
    
    
     
  • 相关阅读:
    SSH框架——Sprign声明式事务
    SSH框架的简化
    Spring声明式事务管理
    简化注解shh框架
    ssh 的搭建
    基础篇-spring包的下载
    基础篇-struts2的搭建
    spring声明式事务管理
    shh简化
    shh(struts+spring+Hibernate)的搭建
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3823984.html
Copyright © 2011-2022 走看看