zoukankan      html  css  js  c++  java
  • 16. 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).

    AC代码:
    class Solution(object):
        def threeSumClosest(self, nums, target):
            if len(nums) < 3: return 0
            ret_num = nums[0] + nums[1] + nums[2]
            nums.sort()
            for i_1st in xrange(len(nums) - 2):
                # remove duplicates
                if i_1st > 0 and nums[i_1st] == nums[i_1st - 1]: continue
                i_2nd, i_3rd = i_1st + 1, len(nums) - 1
                while i_2nd < i_3rd:
                    s = nums[i_1st] + nums[i_2nd] + nums[i_3rd]
                    if s == target:
                        return target
                    if s > target:
                        i_3rd -= 1
                    else:
                        i_2nd += 1
                    if abs(s - target) < abs(ret_num - target):
                        ret_num = s
            return ret_num

    本题和15. 3Sum的双指针解法基本一模一样,只不过本题求的是最接近目标值的和,思想上是一样的。

  • 相关阅读:
    Ubuntu 16 安装ElasticSearch
    二叉树
    归并排序
    快速排序
    Git、Github使用
    445. 两数相加 II
    141. 环形链表
    92. 反转链表 II
    19. 删除链表的倒数第N个节点
    2. 两数相加
  • 原文地址:https://www.cnblogs.com/zhuifengjingling/p/5211596.html
Copyright © 2011-2022 走看看