标签:
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) { int diff=Integer.MAX_VALUE; int res=0; if(nums==null && nums.length==0){ return 0; } Arrays.sort(nums); int len=nums.length; for(int i=0; i<len-2; i++){ if(!(i>0 && nums[i]==nums[i-1])){ int sum=getSum(nums, i, target); if(Math.abs(target-sum)<diff){ diff=Math.abs(target-sum); res=sum; } } } return res; } public int getSum(int[] nums, int index, int target){ int first=nums[index]; int left=index+1; int right=nums.length-1; int diff=Integer.MAX_VALUE; int res=0; while(left<right){ boolean valid=true; if(left>index+1 && nums[left]==nums[left-1]){ left++; valid=false; } if(right<nums.length-1 && nums[right]==nums[right+1]){ right--; valid=false; } if(valid){ int sum=first+nums[left]+nums[right]; if(Math.abs(target-sum)<diff){ diff=Math.abs(target-sum); res=sum; } if((target-sum)>=0){ left++; } else{ right--; } } } return res; } }
标签:
原文地址:http://www.cnblogs.com/incrediblechangshuo/p/5693746.html