zoukankan      html  css  js  c++  java
  • 【leetcode】16. 3Sum Closest

    题目描述:

    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.

    解题方法:

    这道题与15题解题方法思路一致。只是多了一个比较是否是最小差值的步骤.

    具体代码:

     1 public class Solution {
     2    
     3     public static int threeSumClosest(int[] nums, int target) {
     4         List<List<Integer>> results = new ArrayList<List<Integer>>();
     5         if(nums.length<3){
     6             //results.add(new ArrayList<Integer>());
     7             return Integer.MAX_VALUE;
     8         }
     9         if(nums.length==3){
    10             return nums[0]+nums[1]+nums[2];
    11         }
    12         int result=Integer.MAX_VALUE;
    13         int min=Integer.MAX_VALUE;
    14         Arrays.sort(nums);
    15         for(int i=0;i<nums.length-2;i++){
    16             for(int j=i+1;j<nums.length-1;j++){
    17                 for(int index=j+1;index<nums.length;index++){
    18                     int sum = nums[i]+nums[j]+nums[index];
    19                     int dif = Math.abs(sum-target);
    20                     if(dif==0)
    21                         return sum;
    22                     if(dif<min){
    23                         min=dif;
    24                         result=sum;
    25                     }
    26                     //如果sum已经大于target了,则继续往后找第三个数的位置就没有任何意义了。(也是为了充分利用数组有序性)
    27                     if(nums[index]>0 && sum>target)
    28                         break;
    29                         //元素有重复的情况
    30                     while(index+1<nums.length && nums[index+1]==nums[index]){
    31                         index++;
    32                     }
    33                 }
    34                 //元素有重复的情况
    35                 while(j+1<nums.length-1 && nums[j+1]==nums[j]){
    36                     j++;
    37                 }
    38             }
    39             //元素有重复的情况
    40             while(i+1<nums.length-2 && nums[i+1]==nums[i]){
    41                 i++;
    42             }
    43         }
    44         return result;
    45         
    46     }
    47 
    48 }
  • 相关阅读:
    网页日历显示控件calendar3.1
    切换“使用被动式FTP”
    href="javascript:xxx(this);"和onclick="javascript:xxx(this);"的区别
    CSS布局--上中下布局(上下固定,中间自适应)
    css字体颜色动画
    怎么让jQuery支持swipe事件
    html 5 canvas
    javascript面向对象
    WEB相关存储方式
    angularjs
  • 原文地址:https://www.cnblogs.com/godlei/p/5636469.html
Copyright © 2011-2022 走看看