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 }
  • 相关阅读:
    org.json里实现XML和JSON之间对象互转
    Rhino-- JavaScript
    XStream -- a simple library to serialize objects to XML and back again
    [Groovy]转:Groovy 通过 isCase 方法进行分类
    [Groovy]static typing
    JavaScript Succinctly 读后笔记
    [Groovy] Private fields and methods are not private in groovy
    Android 学习之路和App开发框架
    Android自定义xml解析
    Android 动态生成对话框和EditText
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10657852.html
Copyright © 2011-2022 走看看