标签:
/* * 16. 3Sum Closest * 2016-4-15 by Mingyang * 这道题目跟3sum几乎一样 */ public int threeSumClosest(int[] nums, int target) { int len=nums.length; if(len<3||nums==null) return 0; int res=0; int min=Integer.MAX_VALUE; Arrays.sort(nums); for(int i=0;i<len;i++){ int start=i+1; int end =len-1; while(start<end){ int sum=nums[start]+nums[end]+nums[i]; if(sum==target){ return target; }else if(sum<target){ if(target-sum<min){ min=target-sum; res=sum; } start++; }else{ if(sum-target<min){ min=sum-target; res=sum; } end--; } } } return res; }
标签:
原文地址:http://www.cnblogs.com/zmyvszk/p/5397548.html