码迷,mamicode.com
首页 > 其他好文 > 详细

[leedcode 16]

时间:2015-07-07 12:22:55      阅读:113      评论: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).


public class Solution { public int threeSumClosest(int[] nums, int target) { //本题是3Sum的变形,找出最接近target的值 //跟3Sum唯一的不同是,需要增加一个变量min(注意初始化值),内层每次循环时,需要与它进行比较。保留住距离target最小的值 //判断重复的逻辑可有可无,因为本题的输出只是需要返回总结果  Arrays.sort(nums); int res=0; int min=Integer.MAX_VALUE; for(int i=0;i<nums.length;i++){ int left=i+1; // if(i>0&&nums[i]==nums[i-1])continue; int right=nums.length-1; while(left<right){ int temp=nums[i]+nums[left]+nums[right];//注意局部变量的声明,为后面的循环简化表达式 if(temp==target) return res=target; if(temp>target){ if(temp-target<min){ res=temp; min=res-target; } right--; }else{ if((target-temp)<min){ res=temp; min=target-res; } left++; } } } return res; } }

 

[leedcode 16]

标签:

原文地址:http://www.cnblogs.com/qiaomu/p/4626446.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!