zoukankan      html  css  js  c++  java
  • 16. 3Sum Closest(C++)

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

    Solution 

    class Solution {
    public:
      int threeSumClosest(vector<int>& nums, int target) {
        if(nums.size()<3) return 0;
        int number=nums[0]+nums[1]+nums[2];
        std::sort(nums.begin(),nums.end());
        for(int i1=0;i1<nums.size();i1++){
          if(i1>0 && nums[i1]==nums[i1-1]) continue;
          int i2=i1+1;
          int i3=nums.size()-1;
          while(i2<i3){
            int sum=nums[i1]+nums[i2]+nums[i3];
            if(sum==target) return sum;
            if(abs(target-number)>abs(target-sum)) number=sum;
            if(sum>target){
              i3--;
            }else{
              i2++;
            }
          }
        }
        return number;
      }
    };

    
    
  • 相关阅读:
    logging模块
    configparser模块
    hashlib模块
    shutil模块
    json与pickle模块
    random模块
    OS模块
    如何不使用共享内存实现windows与虚拟机中进行文件的传输
    结构体的定义方式(仅定义)
    数据结构练习之寻找顺序表中的主要元素
  • 原文地址:https://www.cnblogs.com/devin-guwz/p/6506372.html
Copyright © 2011-2022 走看看