public class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int diff = Integer.MAX_VALUE, closest = 0;
for (int k=0; k<nums.length2; ++k) {
for (int i=k+1, j=nums.length1; i<j; ) {
int sum = nums[k] + nums[i] + nums[j];
if (sum == target) { return target; }
else if (sum > target) {
if (sumtarget < diff) {
diff = sumtarget;
closest = sum;
}
j;
} else {
if (targetsum < diff) {
diff = targetsum;
closest = sum;
}
++i;
}
}
}
return closest;
}
}
Share my 24line Java code (beats 94.57% run times)


to be honest, i don't know, there is nothing unusual in my code. maybe i am just lucky (getting faster run time THIS TIME). i think it is quite ok if your run time is at the majority part of the run time distribution, which means you have no obvious algorithmic / implementation problem. then, the next thing to do is making the code clean, clear and concise.

public class Solution { public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int diff = Integer.MAX_VALUE, closest = 0; for (int k = 0; k < nums.length2; k++) { if (k > 0 && (nums[k] == nums[k1]))//maybe batter continue; for (int i = k+1, j = nums.length1; i < j; ) { int sum = nums[k] + nums[i] + nums[j]; if (sum == target) { return target; } else if (sum > target) { if (sum  target < diff) { diff = sum  target; closest = sum; } j; while((i < j) && (nums[j] == nums[j+1]))//maybe batter j; } else { if (target  sum < diff) { diff = target  sum; closest = sum; } i++; while((i < j) && (nums[i] == nums[i1]))//maybe batter i++; } } } return closest; } }