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 }
  • 相关阅读:
    角点检测
    25岁董事长给大学生的18条忠告
    10大忠告
    实验常用正交表
    面试必备15题
    专家系统
    深圳租房完全攻略
    你应选什么样的职业?
    托福报名详细过程解说
    Managed Direct3D开发经验浅析
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10657852.html
Copyright © 2011-2022 走看看