LeetCode 016 3Sum Closest

LeetCode 016 3Sum Closest Problem

Download Code
# class Solution(object):
#     def threeSumClosest(self, nums, target):
#         """
#         :type nums: List[int]
#         :type target: int
#         :rtype: int
#         """
class Solution(object):
    def threeSumClosest(self, nums, target):
        ls = len(nums)
        sort_nums = sorted(nums)
        res = nums[0] + nums[1] + nums[2]
        for i in range(ls - 2):
            j, k = i + 1, ls - 1
            while j < k:
                temp = sort_nums[i] + sort_nums[j] + sort_nums[k]
                if abs(target - temp) < abs(target - res):
                    res = temp
                if temp < target:
                    j += 1
                else:
                    k -= 1
        return res


Download 3Sum Closest.py

List of all 3Sum Closest problems

Leetcode 016 3Sum Closest problem solution in python3 with explanation. This is the best place to expand your knowledge and get prepared for your next interview.

:type nums: List[int]

:type target: int

Feedback is the most important part of any website.

If you have any query, suggestion or feedback, Please feel free to contact us.