From 80c333572457080e97dbba2bc9759f3c2850b953 Mon Sep 17 00:00:00 2001 From: Anirban Saha <56464099+Anirbansaha007@users.noreply.github.com> Date: Wed, 19 Oct 2022 14:21:14 +0530 Subject: [PATCH] Solved another leetcode problem in python Description: 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. --- 3sum_closest.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 3sum_closest.py diff --git a/3sum_closest.py b/3sum_closest.py new file mode 100644 index 0000000..deaa42e --- /dev/null +++ b/3sum_closest.py @@ -0,0 +1,25 @@ +class Solution(object): + def threeSum(self, nums): + res = [] + nums.sort() + ls = len(nums) + for i in range(ls - 2): + if i > 0 and nums[i] == nums[i - 1]: + continue + j = i + 1 + k = ls - 1 + while j < k: + curr = nums[i] + nums[j] + nums[k] + if curr == 0: + res.append([nums[i], nums[j], nums[k]]) + while j < k and nums[j] == nums[j + 1]: + j += 1 + while j < k and nums[k] == nums[k - 1]: + k -= 1 + j += 1 + k -= 1 + elif curr < 0: + j += 1 + else: + k -= 1 + return res