题目链接:16. 最接近的三数之和 - 力扣(Leetcode)
题解
连续三天都是双指针,然后今天才发现自己根本不理解双指针。
参考代码
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
| class Solution: def threeSumClosest(self, nums: List[int], target: int) -> int: nums.sort() ret = 1e9 n = len(nums) def check_ans(now, pre): if abs(now - target) <= abs(pre - target): return now return pre for i in range(n): if i - 1 >= 0 and nums[i] == nums[i - 1]: continue j = i + 1 k = n - 1 while j < k: tmp_sum = nums[i] + nums[j] + nums[k] if tmp_sum == target: return target ret = check_ans(tmp_sum, ret)
if tmp_sum > target: k = k - 1 if tmp_sum < target: j += 1 return ret
|