思路
- 排序
- 枚举一个数a
- 双指针移动法确定b和c
- 求和,更新最接近的值
复杂度
T(n)=O(n2)M(n)=O(1)
class Solution {
public int threeSumClosest(int[] nums,int target) {
int sum = nums[0]+nums[1]+nums[2];
int ans = sum;
int minDiff = Math.abs(sum-target);
Arrays.sort(nums);
int len = nums.length;
int l;
int r;
int diff;
for (int i = 0; i+3 <= len; ++i) {
if (nums[i]*3 >= target+minDiff)
break;
l = i+1; r = len-1;
while (l<r) {
sum = nums[i]+nums[l]+nums[r];
diff = Math.abs(sum-target);
if (diff < minDiff) {
minDiff = diff;
ans = sum;
}
if (sum > target)
--r;
else if (sum < target)
++l;
else
return target;
}
}
return ans;
}
}
Runtime: 10 ms, faster than 85.33% of Java online submissions for 3Sum Closest.
Memory Usage: 37.8 MB, less than 100.00% of Java online submissions for 3Sum Closest.