Share my clear 2-pointer solution on python; 116ms


  • 0
    Z
    class Solution(object):
        def threeSumClosest(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: int
            """
            nums.sort()
            ret, left = -2**31, 0
            while left < len(nums)-2 :
                mid, right = left+1, len(nums)-1
                while mid<right:
                    summ = nums[left]+nums[mid]+nums[right]
                    if abs(summ-target) < abs(ret-target): ret = summ
                    if summ == target: return ret
                    elif summ < target:
                        mid += 1
                        while (mid<right) and nums[mid] == nums[mid-1]:
                            mid+=1
                    else:
                        right -= 1
                        while (mid<right) and nums[right] == nums[right+1]:
                            right-=1
                while left < len(nums)-2 and nums[left] == nums[left+1]:
                    left += 1
                left += 1
            return ret

  • 0
    J

    Here is my python solution. They are same, but I guess mine is a bit of clearer than yours. Anyway, thanks for sharing your solution.

    class Solution(object):
        def threeSumClosest(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: int
            """
            nums.sort()
            best=2**31 #record the closest
            best_sum=0  #record the sum when get the closest
            if len(nums)<3:
                return 0
            for first in range(len(nums)-2):
                second,third=first+1,len(nums)-1
                while second<third:
                    cur=nums[first]+nums[second]+nums[third] #current sum
                    if best>abs(target-cur):
                        best=abs(target-cur)
                        best_sum=cur
                    if target-cur>0:
                        second+=1
                    elif target-cur<0:
                        third-=1
                    elif target==cur:
                        return cur
            return best_sum

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.