zoukankan      html  css  js  c++  java
  • 19.1.26 [LeetCode16] 3Sum Closest

    Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    Example:

    Given array nums = [-1, 2, 1, -4], and target = 1.
    
    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

    题意

    跟15差不多,这次是找到最接近给定target的3个数的和

    题解

     1 class Solution {
     2 public:
     3     int threeSumClosest(vector<int>& nums, int target) {
     4         sort(nums.begin(), nums.end());
     5         int tmp=nums[0]+nums[1]+nums[2];
     6         for (int i = 0; i < nums.size(); i++) {
     7             int j = i + 1, k = nums.size() - 1;
     8             while (j < k) {
     9                 int tt = nums[i] + nums[j] + nums[k];
    10                 if (abs(tmp - target) > abs(tt - target))
    11                     tmp = tt;
    12                 if (tt < target)j++;
    13                 else if (tt == target)return target;
    14                 else k--;
    15             }
    16         }
    17         return tmp;
    18     }
    19 };
    View Code

    解法也基本相同

    注定失败的战争,也要拼尽全力去打赢它; 就算输,也要输得足够漂亮。
  • 相关阅读:
    [Tool]使用ConfuserEx混淆代码
    Python_安装官方whl包和tar.gz包
    0017_集合的补充
    0016_练习题d2
    0015_各数据类型方法代码实现
    0014_基本数据类型及常用方法剖析
    0013_运算符
    0012_编码转换
    0011_练习题d1
    0010_while循环
  • 原文地址:https://www.cnblogs.com/yalphait/p/10322967.html
Copyright © 2011-2022 走看看