3Sum Closest

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).

 想来想去想不到什么好的解决方法,只好用最原始的方法,把所有可能的组合列举一遍,选择最优的,O(n^3)。

可以在这个方法上做些优化。 

class Solution:
    def fabs(self,a):
        if a<0:
            return -a
        else:
            return a

    def threeSumClosest(self, num, target):
        num_items=len(num)
        if num_items==3:
            return sum(num)
        num.sort()

        absdiff=self.fabs(target)+self.fabs(num[num_items-1])+self.fabs(num[num_items-2])+self.fabs(num[num_items-3])
        output=absdiff

        for i in range(num_items-2):
            for j in range(i+1,num_items-1):
                sum2=num[i]+num[j]
                k=self.findClosest(num[j+1:num_items],target-sum2,num_items-j-1)
                if target==sum2+k:
                    return sum2+k
                else:
                    absd=self.fabs( target- (sum2+k) )
                    if absd<=absdiff:
                        absdiff=absd
                        output=sum2+k
        return int(output)

    def findClosest(self,num,target,num_items):
        #num is sorted
        if target>=num[num_items-1]:
            return num[num_items-1]
        if target<=num[0]:
            return num[0]
        head=0
        end=num_items-1
        mid=(head+end)//2
        while (end-head)>1:
            if target>=num[mid]:
                head=mid
                mid=(head+end)//2
            else:
                end=mid
                mid=(head+end)//2
        if self.fabs(num[end]-target)-self.fabs(num[head]-target)>0:
            return num[head]
        else:
            return num[end]


if __name__ == '__main__':
    s=Solution()
    n=[1,2,3,4,5,6]    
        print(s.threeSumClosest(n,0))
    print(s.threeSumClosest([1,1,1,1], -100))

 

posted @ 2014-10-13 12:44  clq.lib  阅读(155)  评论(0编辑  收藏  举报