1. 程式人生 > >[LeetCode] 3Sum Closest 最近的三數之和 Python

[LeetCode] 3Sum Closest 最近的三數之和 Python

3Sum Closest:

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
簡單來說,尋找三數之和最接近target的答案,例子如下:
 For example, given array S = {-1 2 1 -4}, and target = 1.

 The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

 解決方法:

和 上一篇3Sum的想法類似,因此程式碼也是在那個的基礎上修改的。只不過因為需要求最近的,而不是固定的,因此所有的判定都需要修改為判斷與與target做差後的絕對值, 因為程式碼大構架和3Sum類似,因此時間複雜度還是O(N^2),程式碼如下:
class Solution(object):
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        nums.sort()
        first=[]
        i=0
        Max=0
        while(i<len(nums)-2):
            if(nums[i]!=nums[i-1] or i==0):
                left=i+1
                right=len(nums)-1
                while(left<right):
                    if(abs(nums[left]+nums[right]+nums[i]-target)==0):
                        Max=target
                        break
                    if(i==0 and left==1 and right==len(nums)-1):
                        Max=nums[left]+nums[right]+nums[i]
                    if(abs(nums[left]+nums[right]+nums[i]-target)<abs(Max-target)):
                        first.append([nums[i],nums[left],nums[right]])
                        Max=nums[left]+nums[right]+nums[i]
                        while(left<right and nums[left]+nums[right]+nums[i]<target):
                            left+=1
                            if(nums[left]!=nums[left-1]):
                                break
                        while(left>right and nums[left]+nums[right]+nums[i]>target):
                            right-=1
                            if(nums[right]!=nums[right+1]):
                                break
                    elif(nums[left]+nums[right]+nums[i]>target):
                        right-=1
                    elif(nums[left]+nums[right]+nums[i]<target):
                        left+=1
            i+=1
        return Max