首页 > 其他 > 详细

LeetCode Notes 3Sum Closest

时间:2015-08-10 19:54:08      阅读:221      评论:0      收藏:0      [点我收藏+]

依旧先来题目:

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).

 

     个人觉得这个是比较简单的一道题哈,我比较擅长这种。唯一比较难的就是最后代码的那个while loop的运用。

     对我来说如果没有想到这个while的话可能就会复杂很多了。主要是不要一直觉得要从头开始3个数字或者从后面开始3个数字这样比较固化的思维。

     而且对于这种杂乱的数列,先sorting整理是很有必要的。

     同样的就是设定初始比较值那个min的时候,想不到怎么设索性就来个最大的不就对了嘛。

public class Solution {
    public int threeSumClosest(int[] nums, int target) {
       if(nums==null||nums.length==0){
           return -1;
       }
       int result=0;
       int min=Integer.MAX_VALUE;
       Arrays.sort(nums);
       for(int i=0;i<nums.length;i++){
           int j=i+1;
           int k=nums.length-1;
           while(j<k){
               int sum=nums[i]+nums[j]+nums[k];
               int diff=Math.abs(sum-target);
               if(diff==0){
                   return sum;
               }
               if(diff<min){
                   min=diff;
                   result=sum;
               }
               if(sum<=target){
                   j++;
               }else{
                   k--;
               }
           }
       }
       return result;
       
       
    }
}

 

LeetCode Notes 3Sum Closest

原文:http://www.cnblogs.com/orangeme404/p/4718860.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!