标签:技术 .com array while color 游离态 div new alt
思路:
以前做过3sum的题,然后直接使用最朴素的三重循环,感觉方法太笨了,借用大佬的方法;
from:http://www.cnblogs.com/grandyang/p/4510984.html
先排序,然后卡住一个位置的元素,其他两个坐标处于游离态。
class Solution { public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int closest = nums[0] + nums[1] + nums[2]; int diff = Math.abs(closest - target); for(int i = 0; i < nums.length - 2;i++) { int left = i + 1,right = nums.length - 1; while(left < right) { int newSum = nums[i] + nums[left] + nums[right]; int newDiff = Math.abs(newSum - target); if(newDiff < diff) { diff = newDiff; closest = newSum; } if(newSum < target) left++; else right--; } } return closest; } }
标签:技术 .com array while color 游离态 div new alt
原文地址:http://www.cnblogs.com/xeal/p/7488841.html