zoukankan      html  css  js  c++  java
  • 3Sum Closest

    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思路类似,只是每次都要记录目前最优结果,代码如下:

    class Solution(object):
        def threeSumClosest(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: int
            """
            nums.sort()
            i = 0
            res = nums[0]+nums[1]+nums[2]
            while i < len(nums):
                l = i+1
                r = len(nums)-1
                while l < r:
                    if l < r and nums[i]+nums[l]+nums[r] == target:
                        return target
                    while l < r and nums[i]+nums[l]+nums[r] < target:
                        if abs(nums[i]+nums[l]+nums[r]-target) < abs(res-target):
                            res = nums[i]+nums[l]+nums[r]
                        while l < r and nums[l+1] == nums[l]:
                            l += 1
                        l += 1
                    while l < r and nums[i]+nums[l]+nums[r] > target:
                        if abs(nums[i]+nums[l]+nums[r]-target) < abs(res-target):
                            res = nums[i]+nums[l]+nums[r]
                        while l < r and nums[r-1] == nums[r]:
                            r -= 1
                        r -= 1
                i += 1
            return res
  • 相关阅读:
    C语言基础-第一章
    C语言基础-第三章
    C语言基础-第五章
    怎样在WIN7系统下安装IIS
    Asp.Net中使用水晶报表(下)
    Asp.Net中使用水晶报表(中)
    Asp.Net 中使用 水晶报表(上)
    A1112. Stucked Keyboard
    A1111. Online Map
    A1110. Complete Binary Tree
  • 原文地址:https://www.cnblogs.com/Peyton-Li/p/8094622.html
Copyright © 2011-2022 走看看