In the Leetcode 3Sum Closest problem solution in Python programming Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target.
Return the sum of the three integers.
You may assume that each input would have exactly one solution.
Leetcode 3Sum Closest problem solution in Python programming
class Solution(object):
def threeSumClosest(self, nums, target):
nums.sort()
minSum = float('inf')
for anchorIdx in range(len(nums) - 2):
leftIdx = anchorIdx + 1
rightIdx = len(nums) - 1
while leftIdx < rightIdx:
anchor = nums[anchorIdx]
second = nums[leftIdx]
third = nums[rightIdx]
currThreeSum = [anchor, second, third]
currSum = sum(currThreeSum)
# compare currSum with minSum w.r.t target
if abs(currSum - target) < abs(minSum - target):
minSum = currSum
# shift the left or right index
if currSum < target:
leftIdx += 1
elif currSum > target:
rightIdx -= 1
else:
return currSum
return minSum
Also read,
- Leetcode 3Sum Closest problem solution in C++
- Leetcode 3Sum Closest problem solution in Java
- Leetcode 3Sum Closest problem solution in C
- Leetcode 3Sum Closest problem solution in C#