zoukankan      html  css  js  c++  java
  • 3Sum 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. 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

    和3Sum的思路基本一样。也是固定起点后,双指针遍历。

     1 public class Solution {
     2     public int threeSumClosest(int[] nums, int target) {
     3         if (nums == null || nums.length < 3) {
     4             return 0;
     5         }
     6         int length = nums.length;
     7         Arrays.sort(nums);
     8         int min = Integer.MAX_VALUE;
     9         int result = nums[0] + nums[1] + nums[2];
    10         for (int i = 0; i < length - 2; i++) {
    11             // Avoid duplicates
    12             if (i > 0 && nums[i] == nums[i - 1]) {
    13                 continue;
    14             }
    15             int l = i + 1, r = length - 1;
    16             while (l < r) {
    17                 int sum = nums[i] + nums[l] + nums[r];
    18                 int sub = Math.abs(sum - target);
    19                 if (sub == 0) {
    20                     return sum;
    21                 } else if (min > sub) {
    22                     min = sub;
    23                     result = sum;
    24                 }
    25                 if (sum > target) {
    26                     r--;
    27                     // Avoid duplicates
    28                     while (l < r && nums[r] == nums[r + 1]) {
    29                         r--;
    30                     }
    31                 } else if (sum < target) {
    32                     l++;
    33                     // Avoid duplicates
    34                     while (l < r && nums[l] == nums[l - 1]) {
    35                         l++;
    36                     }
    37                 }
    38             }
    39         }
    40         return result;
    41     }
    42 }
  • 相关阅读:
    Busybox制作ARM(iTOP4412) 根文件系统
    01.高并发底层原理
    设计模式
    高并发实战
    # 记一次shell编写
    shell if条件语句
    scrapy使用
    整理JAVA知识点--基础篇,能力有限不足地方请大神们帮忙完善下
    mybatis-generator使用
    优先级队列实现
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4937699.html
Copyright © 2011-2022 走看看