zoukankan      html  css  js  c++  java
  • 3 Sum Closest 解答

    Question

    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.

    Example

    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

    Similar with 3 Sum. Time complexity is O(n2)

     1 public class Solution {
     2     public int threeSumClosest(int[] numbers ,int target) {
     3         int length = numbers.length;
     4         Arrays.sort(numbers);
     5         int min = Integer.MAX_VALUE;
     6         int result = numbers[0] + numbers[1] + numbers[2];
     7         for (int i = 0; i < length - 2; i++) {
     8             if (i > 0 && numbers[i] == numbers[i - 1])
     9                 continue;
    10             int l = i + 1, r = length - 1;
    11             while (l < r) {
    12                 while (l < r && numbers[l] == numbers[l + 1])
    13                     l++;
    14                 while (l < r && numbers[r] == numbers[r - 1])
    15                     r--;
    16                 int sum = numbers[i] + numbers[l] + numbers[r];
    17                 if (sum > target)
    18                     r--;
    19                 else if (sum < target)
    20                     l++;
    21                 else
    22                     return target;
    23                 int tmp = Math.abs(sum - target);
    24                 if (tmp < min) {
    25                     min = tmp;
    26                     result = sum;
    27                 }
    28             }
    29         }
    30         return result;
    31     }
    32 }
  • 相关阅读:
    210111做个期望值低的人
    error_1 springboot `com.mysql.jdbc.Driver'问题
    error_2 springboot mysql时区设置
    17_springboot Restful风格
    15_JSON springboot
    13_springboot文件上传
    12_springboot myBatis crud
    11_springboot JPA crud
    Swagger导出MarkDown
    Docker 使用中的一些问题
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4890835.html
Copyright © 2011-2022 走看看