2 Add Two Numbers

题目描述:

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

Example 1:

 given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2\. (-1 + 2 + 1 = 2).

题目翻译

给定包含 n 个正数的数组 S ,找出 S 中3个元素的和,使其最接近给定数值,假设只有一个最优解

示例1:

Input : S={-1 2 1 -4}, target = 1.
Output : 2

解题方案

标签: Array

思路:

  • 首先对给定的数组进行排序,然后从0到数组元素长度len-2开始循环,对于每层循环,定义两个指针一个left指向i+1,right指向数组的尾部,然后开始判断i,left和start指向的元素之和是否更接近给定的元素,如果接近则更新,然后判断3个元素的和是大于给定的元素还是小于给定的元素,大于的话left指针加1,小于的话right指针减1;

代码:

class Solution(object):
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        if not nums:
            return []

        sortNum = sorted(nums)
        closest = sys.maxint
        for i in range(len(sortNum)):
            left, right = i + 1, len(sortNum) - 1
            while left < right:
                Sum = sortNum[i] + sortNum[left] + sortNum[right]
                if Sum == target:
                    return Sum
                elif Sum > target:
                    right -= 1
                else:
                    left += 1
                closest = Sum if abs(Sum - target) < abs(closest - target) else closest 

        return closest

参考资料

results matching ""

    No results matching ""