zoukankan      html  css  js  c++  java
  • leetcode: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).
    给定一个含有n个数的数组S找到其中三个数使其最接近给定的数target,你可以假定每一次数组输入都有唯一的一个解。
    算法思路:① 这个题和上一个题http://www.cnblogs.com/zhaolizhen/p/3Sum.html求三个数的和类似,但是要简单的多,其实还有更简单的方法,
    抱着试试的心态,麻烦的穷举算法也能通过。
         ② 设置三个for循环,设置两个变量int temp=0;int n=Integer.MAX_VALUE;分别记录得到离target最近的值以及和target的差值。
    代码设计:
     1 class Solution{
     2     public int threeSumClosest(int[] num, int target) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         int temp=0;//记录最近的值
     6         int n=Integer.MAX_VALUE;//记录和target的差值
     7         for(int i=0;i<num.length;i++){//三重循环时间复杂度太高, 可是也没想起其他好办法
     8             for(int j=i+1;j<num.length;j++){
     9                 for(int k=j+1;k<num.length;k++){
    10                     if(Math.abs(num[i]+num[j]+num[k]-target)<n){
    11                         n=Math.abs(num[i]+num[j]+num[k]-target);
    12                         temp=num[i]+num[j]+num[k];
    13                     }
    14                 }
    15             }
    16         }
    17         return temp;
    18     }
    19 }
       这个题还有更简单的解法,就是对这个数组排序,然后设置两个指针,一个从前往后,一个从后往前进行遍历,判断三个数的和和target的差值,
    记录下最小的并返回。

  • 相关阅读:
    C#基本数据类型
    ASP.NET MVC 实现二级域名
    asp.net下通过泛解析和伪静态实现二级域名的实现方法
    Web Forms vs Web MVC
    WebForm页面生命周期及asp.net运行机制
    波函数坍缩
    whoami
    wstngfw中使用虚拟IP映射内网IP
    Thread-specific data(TSD)线程私有数据
    Libev库学习
  • 原文地址:https://www.cnblogs.com/zhaolizhen/p/3SumClosest.html
Copyright © 2011-2022 走看看