Python solution time limit exceeded


  • 0
    Z

    Hi all,

    I have a python solution for this question, but leetcode indicates time limit exceeded, can any one help me to modify my code?

    class Solution:
        # @param {integer[]} nums
        # @param {integer} target
        # @return {integer}
        def threeSumClosest(self, nums, target):
            self.nums = nums
            self.target = target
            nums = sorted(nums)
            n = len(nums)
            if target >= nums[n-1]+nums[n-2]+nums[n-3]:
                return nums[n-1]+nums[n-2]+nums[n-3]
            elif target <= nums[0]+nums[1]+nums[2]:
                return nums[0]+nums[1]+nums[2]
            else:
                k1 = max(nums)-min(nums)
                for i in xrange(n-1):
                    j = i+1
                    while nums[i]+nums[j] < target:
                        k = target-(nums[i]+nums[j])
                        p = sorted(nums)
                        p.remove(p[j])
                        p.remove(p[i])
                        if k in p:
                            return target
                        else:
                            if k1 > k:
                                k1 = k
                            if j < n-1:
                                j = j+1
                            else:
                                break
                return k1+target
    

    thanks


Log in to reply
 

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