Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

16. 3Sum Closest #174

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

public class Solution { public int threeSumClosest(int[] nums, int target) { int res = nums[0] + nums[1] + nums[nums.length-1]; Arrays.sort(nums); for(int i = 0; i < nums.length - 2; i++) { int lo = i + 1, hi = nums.length - 1; while(lo < hi) { int flag = nums[i] + nums[lo] + nums[hi]; if(flag > target) { hi--; } else { lo++; } if(Math.abs(flag - target) < Math.abs(res - target)) { res = flag; } } } return res; } }