DEV Community

Takahiro Kudo
Takahiro Kudo

Posted on

1

LeetCode "3Sum Closest"

I could not solve this problem, so I referred to this😢

3Sum Closest

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:

        nums.sort()

        len_nums = len(nums)
        closest = nums[0] + nums[1] + nums[len_nums - 1]
        for i in range(len_nums - 2):
            left = i + 1
            right = len_nums - 1
            while left < right:
                sum_nums = nums[i] + nums[left] + nums[right]
                if sum_nums == target:
                    return target
                else:
                    if abs(sum_nums - target) < abs(closest - target):
                        closest = sum_nums
                    if sum_nums < target:
                        left += 1
                    else:
                        right -= 1

        return closest
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay