ninehills / blog

https://ninehills.tech
758 stars 68 forks source link

LeetCode-16. 3Sum Closest #25

Closed ninehills closed 7 years ago

ninehills commented 7 years ago

问题

https://leetcode.com/problems/3sum-closest/#/description

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.

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

解答

#coding=utf8
class Solution(object):
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        nums.sort()
        closest = 0
        ret = []
        for i in range(len(nums) - 2):
            if i > 0 and nums[i-1] == nums[i]:
                # 如果和前一位相等,直接忽略,避免重复结果
                continue
            l = i + 1
            r = len(nums) - 1
            while l < r:
                s = nums[l] + nums[r] + nums[i] - target
                if closest == 0 or abs(s) < closest:
                    closest = abs(s)
                    ret = (nums[l], nums[r], nums[i])
                if s == 0:
                    return target
                elif s > 0:
                    r = r - 1
                else:
                    l = l + 1
        print ret
        return ret[0] + ret[1] + ret[2]

print Solution().threeSumClosest([-1, 2, 1, -4], 1)
print Solution().threeSumClosest([0, 0, 0], 1)
print Solution().threeSumClosest([0, 1, 2], 3)
ninehills commented 7 years ago

20170725