zoukankan      html  css  js  c++  java
  • 最接近的三数之和

    给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

    例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.

    与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

     1 public class T16 {
     2     public int threeSumClosest(int[] nums, int target) {
     3         if (nums == null || nums.length < 3) {
     4             return 0;
     5         }
     6         Arrays.sort(nums);
     7         int res = nums[0] + nums[1] + nums[2];
     8         for (int i = 0; i < nums.length - 2; i++) {
     9             int l = i + 1;
    10             int r = nums.length - 1;
    11             while (l < r) {
    12                 int sum = nums[i] + nums[l] + nums[r];
    13                 if (Math.abs(sum - target) < Math.abs(res - target)) {
    14                     res = sum;
    15                 }
    16                 if (sum > target) {
    17                     r--;
    18                 } else if (sum < target) {
    19                     l++;
    20                 } else {
    21                     return sum;
    22                 }
    23             }
    24         }
    25         return res;
    26     }
    27 }
    一回生,二回熟
  • 相关阅读:
    渣渣的python的上路
    【tyvj 2038】诡异的数学题
    codeforces_733_A
    NOIP2011 选择客栈
    NOIP 2012 同余方程
    灵渊(seals.cpp/c/pas)
    NOIP 2012 开车旅行
    Mybatis初步详细配置
    SpringMVC之编程式校验
    Spring整合MyBaytis
  • 原文地址:https://www.cnblogs.com/zzytxl/p/12504765.html
Copyright © 2011-2022 走看看