美文网首页
LeetCode 3Sum Closest

LeetCode 3Sum Closest

作者: manyGrasses | 来源:发表于2019-02-02 15:07 被阅读0次

题目

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).


解法

解法和三数之和一样,需要先对数据进行一次排序, 之后每次固定第一个数,按情况移动中间数或者尾数,在判断的时候需要由于不是精确等于,因此要用差值进行判断,每次如果差值更小,就替换现有解。

代码示例

class Solution:
    # @return an integer
    def threeSumClosest(self, num, target):
        num.sort()
        result = num[0] + num[1] + num[2]
        for i in range(len(num) - 2):
            j, k = i+1, len(num) - 1
            while j < k:
                sum = num[i] + num[j] + num[k]
                if sum == target:
                    return sum
                
                if abs(sum - target) < abs(result - target):
                    result = sum
                
                if sum < target:
                    j += 1
                elif sum > target:
                    k -= 1
            
        return result


相关文章

网友评论

      本文标题:LeetCode 3Sum Closest

      本文链接:https://www.haomeiwen.com/subject/zusdsqtx.html