Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode-16. 3Sum Closest #25

Closed
ninehills opened this issue Jul 25, 2017 · 1 comment
Closed

LeetCode-16. 3Sum Closest #25

ninehills opened this issue Jul 25, 2017 · 1 comment
Labels

Comments

@ninehills
Copy link
Owner

问题

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
Copy link
Owner Author

20170725

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant