1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| class Solution{ public int threeSumClosest(int[] nums, int target) { int sub = Integer.MAX_VALUE; int sum =0; int length = nums.length; for(int i=0;i<length;i++){ for(int j=i+1;j<length;j++){ for(int k=j+1;k<length;k++){ if(Math.abs(nums[i]+nums[j]+nums[k]-target) < sub){ sum = nums[i]+nums[j] + nums[k]; sub = Math.abs(nums[i]+nums[j] + nums[k] -target); } } } } return sum; } } public int threeSumClosest2(int[] nums, int target) { Arrays.sort(nums); int nearNum = nums[0] + nums[1] + nums[2]; for(int i=0;i< nums.length-2;i++){ int l = 0; int r = nums.length-1; while(l<r){ int targetNum = nums[l]+nums[i]+nums[r]; if(Math.abs(targetNum - target ) < Math.abs(nearNum -target )){ nearNum = targetNum; } if(targetNum > target){ r--; }else if (targetNum < target){ l++; }else{ return target; } } } return nearNum; } }
|