• 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差不多,不过本题要求求解与target最接近的三数之和。同理,先对数组进行排序,然后两边夹逼。在设置初始最接近的数字时,设为int型最大值。

    运行时间:15ms

     1 class Solution {
     2 public:
     3     int threeSumClosest(vector<int>& nums, int target) {
     4         //if(nums.size() < 3) return 0;
     5         if(nums.size() == 3) return nums[0] + nums[1] + nums[2];
     6         sort(nums.begin(), nums.end());
     7         int closest = pow(2, 31) - 1, result = 0;
     8         
     9         for(int a = 0; a < nums.size() - 2; a++){
    10             int b = a + 1, c = nums.size() - 1;
    11             while(b < c){
    12                 int diff = nums[a] + nums[b] + nums[c] - target;
    13                 if(diff < 0) b++;
    14                 else if(diff > 0) c--;
    15                 else return target;
    16                 
    17                 if(abs(diff) < closest){
    18                     result = diff + target;
    19                     closest = abs(diff);
    20                 }
    21             }
    22         }
    23         return result;
    24     }
    25 };
  • 相关阅读:
    29-赫夫曼树
    28-线索化二叉树
    27-顺序存储二叉树
    26-二叉树的遍历查找和删除
    25-二叉树的概念
    24-逻辑结构分析
    23-哈希表
    22-查找算法
    21-堆排序
    Mui-列表/table-view
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4495146.html
Copyright © 2020-2023  润新知