3Sum Smaller

Problem: 3Sum Smaller

The solution is similar to 3Sum. The difference lies in once we get a sum smaller than target, we may get more than 1 answer to add.

Code in Python:

class Solution(object):
    def threeSumSmaller(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        nums = sorted(nums)
        n = len(nums)
        ans = 0
        for i in xrange(n-2):
            l, r = i+1, n-1
            while l < r:
                sum = nums[i] + nums[l] + nums[r]
                if sum < target:
                    ans += r-l
                    l += 1
                else:
                    r -= 1
        return ans

results matching ""

    No results matching ""