zoukankan      html  css  js  c++  java
  • [leetcode]16. 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).

    题意:

    给定一个数组和一个值target,找出其中3个元素,使其加起来最接近target。

    Solution1:Two Pointers(left and right to meet each other)

    1. Sort the array (coz we must check the duplicates) 

    2. Lock one pointer and do two sum with the other two 

    3. Keep updating the gap between given target with result. The smaller gap is, the closer result is.

    code

     1 /*
     2   Time Complexity: O(n^2). For each locked item, we need traverse the rest of array behind such item.  
     3   Space Complexity: O(1).  We only used constant extra space.
     4 */
     5 class Solution {
     6      public int threeSumClosest(int[] nums, int target) {
     7         int result = 0;
     8         int minGap = Integer.MAX_VALUE;
     9         Arrays.sort(nums);
    10         for (int i = 0; i < nums.length; i++) {
    11             int j = i + 1;
    12             int k = nums.length - 1;
    13             while (j < k) {
    14                 int sum = nums[i] + nums[j] + nums[k];
    15                 int gap = Math.abs(target - sum);
    16                 // keep updating the gap. The smaller gap is, the closer result is.
    17                 if (gap < minGap) {
    18                     result = sum;
    19                     minGap = gap;
    20                 }
    21                 // two pointers(left and right to meet each other)
    22                 if (sum < target) {
    23                     j++;
    24                 } else {
    25                     k--;
    26                 }
    27             }
    28         }
    29         return result;
    30     }
    31 }
  • 相关阅读:
    多项输入
    输出多项数据
    圆的面积
    计算并显示
    半径计算圆的周长和面积
    三角形的面积
    显示数据二进制形式
    将一批数据以二进制形式存放在磁盘文件中
    读入字符存入磁盘文件
    数组送到磁盘文件存放
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10657852.html
Copyright © 2011-2022 走看看